Suicide: Objective-C objects by calling their own methods -dealloc

Is it good practice for an object in Objective-C to commit suicide? That is, for an object announcing [self dealloc]where an -deallocordered wind permits, as usual? What are the main risks?

Be that as it may, I have a specific example - a custom timer object that extends NSObject and contains an instance of NSTimer and NSUInteger, which is set to limit the number of times the timer fires. When time runs out, the object tells the timer -invalidate, and then commits suicide by calling its method -dealloc. Since this is automatic, we don’t worry about tracking an object or critically knowing when it’s the right moment to release it.

See my post above here for a more detailed explanation .

+1
source share
2 answers

Is it good practice for an object in Objective-C to commit suicide? That is, for an object declaring [self dealloc], where -dealloc allows an ordered wind, as usual? What are the main risks?

No.

The only time you should ever write a call to dealloc is to send dealloc to a super object in the dealloc method of one of your classes. There are no exceptions.

If you try to send dealloc to an object at any other time, you risk leaving other objects with dangling pointers. Do not do this.


- ? , . " ", - . , init, , nil ( , , alloc self).

+8

-dealloc. [self release], 0 -dealloc.

+9

Source: https://habr.com/ru/post/1754045/


All Articles