Who calls the dealloc method and when in Objective C?

前端 未结 4 768
深忆病人
深忆病人 2021-02-05 14:06

When a custom class is created in Objective C, when and how is the dealloc method called? Is it something that I have to implement somehow in my class?

4条回答
  •  甜味超标
    2021-02-05 14:43

    dealloc is called as a result of memory management. Once an objects "retainCount" reaches 0 then a dealloc message is automatically sent to that object.

    You should never call dealloc on objects unless it is a call to [super dealloc]; at the end of an overridden dealloc.

    -(void)dealloc
    {
        [ivar release]; //Release any retained variables before super dealloc
    
        [super dealloc]; //Only place in your code you should ever call dealloc
    }
    

    And according to the -[NSObject dealloc] discussion

    You never send a dealloc message directly. Instead, an object’s dealloc method is invoked indirectly through the release NSObject protocol method (if the release message results in the receiver's retain count becoming 0). See Memory Management Programming Guide for more details on the use of these methods.

提交回复
热议问题