IOS attribute Error

Source: Internet
Author: User

1. Self. Name = [[nsstring alloc] init];

2. _ name = [[nsstring alloc] init];

Self. Name = @ "Whatif ";

The above two methods: Most people think that the _ name app count in 1 and 2 is 2, because "self. name = "(set method), alloc, reference count is 2; for 2: alloc is used, and" self. name = "(set method), reference count is 2.

In fact, the above statement is wrong !!!

The correct answer is: The reference count of _ name in 1 is 2, and the reference count of _ name in 2 is 1.

The reason is the internal implementation of the Set Method:

-(Void) setname :( nsstring *) name {

If (_ name! = Name ){

[_ Name release];

[_ Name = Name retain];

}}

For the 1st cases: the "self. name = ", because _ name is not initialized, It is nil. When the set method is called, [_ name release] does not work. It is not reduced by 1, but [name retain, the _ name reference count is added once, and then alloc is used. The reference count of _ name is changed to 2.

In 2nd cases: alloc is used first, and the _ name reference count is changed to 1. Because _ name is not nil, when the set method is called, [_ name release] reduces the reference count by 1, in this case, the reference count of _ name is 0; when [name retain] is used once, the reference count is 1.

 

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.