Objective C iPhone when to set object references to nil

前端 未结 1 520
[愿得一人]
[愿得一人] 2021-01-31 23:18

I have been developing with objective C and the Cocoa framework for quite some time now. However it is still not absolutely clear to me, when am I supposed to set object referen

相关标签:
1条回答
  • 2021-01-31 23:49

    Say you have a pointer myView defined in your class' interface:

    @interface MyClass {
       UIView *myView;
    }
    
    @end
    

    Then in your code, at some point, you may release that variable:

    [myView release];
    

    After you do that, myView, the pointer, won't be pointing to nil, but will be pointing to a memory address of an object that may not exist anymore (since you just released it). So, if you happen to do something after this, like:

    [myView addSubview:otherView];
    

    you'll get an error.

    If, on the other hand, you do this:

    [myView release];
    myView = nil;
    ...
    [myView addSubview:otherView];
    

    the call to addSubview will not have any negative impact, since messages to nil are ignored.

    As a corollary, you may see suggestions of using retain properties, such as:

    @property(retain) UIView *myView;
    

    and then in the code, just do:

    self.myView = nil;
    

    By doing that, the synthesized accessor will release the old object and set the reference to nil in one line of code. This may prove useful if you want to make sure all your properties are both released and set to nil.

    One thing that you must never forget, is that memory management is done by means of retain release calls, and not by means of assigning nil. If you have an object with a retain count of 1, and assign nil to it's sole variable, you'll be leaking memory:

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,10,10)];
    view = nil;
    // You just leaked a UIView instance!!!
    
    0 讨论(0)
提交回复
热议问题