Do not use accessor in initialization methods and Dealloc methods Methods

Source: Internet
Author: User

Apple says in the Advanced Memory Management Programming Guide:

Don ' t use Accessor Methods in Initializer Methods and dealloc The only places you shouldn ' t use Accessor Methods to set an Instance variable is in initializer methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an Init method as follows:

- init {    self = [super init];    if (self) {        _count = [[NSNumber alloc] initWithInteger:0];    }    return self;}

The only place where you don't need to use accessor methods is initializer and dealloc. There is no explanation in Apple's official document why. After a review, the main reason is that the state of the object is uncertain, has not been fully initialized, and caused some problems.

For example, this class or subclass overrides the Setmethod, which calls some other data or methods that require a fully initialized object. In Init, the state of the object is indeterminate.

For example, a subclass overrides the set method and carries out some subclass-specific operations, which can cause the problem to be sent if the parent class uses accessor Methods directly in Init.

Other problems are, like triggering KVO notification, and so on.

In short, remember that this principle is the most important to remember in development.

In the development, I found that some people are inadvertently or do not know the direct use of Self.property = XXX in the Init method to assign values, leaving some hidden trouble.

Do not use accessor in initialization methods and Dealloc methods Methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.