The difference between self and _ (the difference between self and underscore)

Source: Internet
Author: User

At the same time we found that when we visited the variables we declared, there was self. And the way of access that begins with "_", what is the difference between these two ways?

Let's take a look:

@property (retain, nonatomic) NSMutableArray *nameArray;self.nameArray是访问属性的,而_nameArray是访问实例变量的.

property is an integration of instance variables plus the Get,set method, and he is primarily responsible for an external access to an interface!

Instance variables can only be accessed in this class and cannot be accessed externally!

The general principle:

Use "_" when accessing variables within a class;

The "." syntax is used to access variables of this class outside of the class, which is other classes;

Note: In case of manual memory management:

Use the "." syntax to initialize a variable, there is a memory leak issue:

self.nameArray = [NSMutaleArray alloc] init];

The problem with the above code is that when Self.namearray is equivalent to calling the Set method, the reference count is +1, and the reference count is +1 again after Alloc.
In our final Dealloc release, the reference count was reduced only once, and the release was not complete, causing a memory leak.

The workaround is to initialize and access the variables with "_", so that there is no memory problem, but it is not a smart approach, but it does work.
_nameArray = [NSMutaleArray alloc] init];

The above is "." and "_" in the use of the simple difference.

If this is not the case with arc (automatic management of memory), it is better to look at it from the coding specification.

The difference between self and _ (the difference between self and underscore)

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.