search

Home  >  Q&A  >  body text

objective-c - OC It is better not to use properties in initialization methods or dealloc, why?

I have seen this description several times: It is best not to use attributes in the initialization method or dealloc, because you cannot be sure whether self is actually calling the instance you want. Why is this?

習慣沉默習慣沉默2838 days ago722

reply all(3)I'll reply

  • 漂亮男人

    漂亮男人2017-05-02 09:31:36

    Where did you see it? Those are all things of the past, there are no restrictions in ARC, you can use it as you like.

    In the old days of manual memory management, calling properties would involve adding and subtracting reference counters, and self = [super ...] 初始化的对象不一定是当前类的对象,可能是“变体”或私有类(objc里的class有 classmetaclass 的区别),所以在你不知道属性 setter 方法里到底是怎么加减引用计数器的情况下,你就只针对 ivar just retain and release.

    - (id)initWithString:(NSString *)str
    {
        self = [super init];
        if (self) {
            _foo = [str copy];
        }
        return self;
    }
    
    - (void)dealloc
    {
        [_foo release];
        [super dealloc];
    }

    retain(copy,new) and release appear in pairs

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-02 09:31:36

    Because it will generate circular references, such as delegate, and then it will never be released

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-02 09:31:36

    Because there are categories (Category), setters, getters, KVO, etc. that need to be paid attention to
    The most important thing is because of the classification. Grammar can call the attributes and methods of the classification, but _ does not work, you need to pay attention

    reply
    0
  • Cancelreply