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.