OBJECTIVE-C 2.0 adds the dot syntax, which is used to simply invoke the accessor of the member variable. Equivalent to Java getter and setter. Because under normal circumstances, writing a accessor for beginners, it is quite easy to make mistakes. For example, there is a member variable of NSString * called name. One of the wrong spellings is:
-(void) SetName: (NSString *) newName { = newName;}
Java classmate certainly can't think of the above code what is wrong? The reason is that objective-c needs to be responsible for the release of memory. So you need to change the reference before the original object release, the new object, also need to retain, the code is changed to this:
-(void) SetName: (NSString *) newName { [name release]; = [newName retain];}
Beginners may think this is right, in fact, it is still wrong, if NewName and name are pointing to the same object, and this object retain count is only 1. After the name release, the object is recycled. So it should be changed to:
-(void) SetName: (NSString *) newName { if (name! = newName) { [name release]; = [newName retain];} }
This is a correct set function, Java classmates must be frightened, although know so, but this is more troublesome than Java. As a result, OBJECTIVE-C allows programmers to automatically generate these codes using @property + @synthesize keywords. So the OBJECTIVE-C programmer was happy. Most of the time there is no need to write getter and setter.
Be careful, however, that the objective-c accessor cannot be used in the INIT and DEALLOC functions! If you write this in Dealloc, there is a problem:
-(void) dealloc { = nil; [Super Dealloc]}
Apple has an article in its developer document library that specializes in cocoa memory management.
The 16th page of the article has a section titled: Don ' t use Accessor Methods in Initializer Methods and Dealloc.
The article says: The only place you should not use accessor is the init function and the Delloc function. In the Init function, for a _COUNT member variable you should assign a value like this:
-(void) init { = [Super init]; if (self) { = [[NSNumber alloc] Initwithinteger:0]; } return Self ;}
For an init function with parameters, you should implement the following:
-(void) Initwithcount: (NSNumber *) startingcount { = [Super init]; if (self) { = [startingcount copy]; } return Self ;}
For the dealloc, the corresponding wording should be the release:
-(void) dealloc { [_count release]; [Super Dealloc];}
But the more depressed is, the article finally did not say why not! Go to StackOverflow on the search, more unreliable saying is so less once function call, faster. The more plausible argument is that, in Init and dealloc, the presence or absence of an object is uncertain, so sending a message to an object may not be successful.
A tribute to the great God, "don't use accessor in init and dealloc functions," from the blog of Tang Qiao, the Great God.
Do not use accessor in the init and DEALLOC functions