The difference between accessing an attribute and accessing an instance variable

Source: Internet
Author: User

1, because do not pass Objective-c "method Dispatch" step, so direct access to the instance variable speed will be relatively fast. In this case, the code generated by the compiler accesses the block of memory that holds the object instance directly;

2. When accessing an instance variable directly, it does not invoke its "set method", which bypasses the "Memory management semantics" defined for setting the related property;

3, if the instance variable is accessed directly, then the "Key value observation" (Key-value OBSERVING,KVO) notification will not be triggered. Whether this will cause problems and depends on the specific object behavior.

Therefore, a reasonable compromise is that when the instance variable is written, it is done by its "set method", and when the instance variable is read, it is accessed directly. This method can not only increase the speed of the read operation, but also control the write operation to the property. The primary reason for writing instance variables through the set method is to ensure that the memory management semantics of the relevant properties are enforced. However, there are several issues to be aware of when choosing this approach:

1. The instance variable should always be accessed directly in the Init method and Dealloc method, because the subclass may "overwrite" (override) the setting method;

2, "lazy initialization" (lay initialization), in which case the property must be accessed through the Get method, otherwise the instance variable will never be initialized.

The difference between accessing an attribute and accessing an instance variable

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.