Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is highly unlikely that an object would be in a position to cause its own release/deallocation if your code is designed properly. So yes, the situation you describe is indicative of bad coding practice, and can in fact cause the program to crash. Here is an example:</p> <pre><code>@interface Widget : NSObject @property (retain) NSMutableArray *array; @end @implementation Widget @synthesize array; - (id)init { self = [super init]; if(self) { array = [[NSMutableArray alloc] init]; [array addObject:self]; } return self; } - (void)dealloc { NSLog(@"Deallocating!"); [array release]; [super dealloc]; } - (void)removeSelf { NSLog(@"%d", [array count]); [array removeObject:self]; NSLog(@"%d", [array count]); } @end </code></pre> <p>and then this code is in another class:</p> <pre><code>Widget *myWidget = [[Widget alloc] init]; [myWidget release]; // WHOOPS! [myWidget removeSelf]; </code></pre> <p>The second call to NSLog in <code>removeSelf</code> will cause an EXC_BAD_ACCESS due to the fact that <code>array</code> has been deallocated at that point and can't have methods called on it.</p> <p>There are at least a couple mistakes here. The one that ultimately causes the crash is the fact that whatever class is creating and using the <code>myWidget</code> object releases it before it is finished using it (to call removeSelf). Without this mistake, the code would run fine. However, MyWidget shouldn't have an instance variable that creates a strong reference to itself in the first place, as this creates a retain cycle. If someone tried to release <code>myWidget</code> without first calling <code>removeSelf</code>, nothing would be deallocated and you'd probably have a memory leak.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload