Just another iPhone Blog
Assigning Values to Properties – The Common Pitfall
No prizes for saying the above statement assigns a view which will act as a content view for appropriate UIViewController.
What we have to keep in mind is the fact that there is a potential leak in above statement.
Programmers, especially from a C++ background, tend to make this very common mistake as they think that they are assigning a value to a property of a class.
[Some blame has to go to creators of Objective C 2.0 language, who has created a slight confusion in using dot[.] notation to access properties]
Objective C 2.0 has introduces a new rather a different concept in order to access the members of a Class.
Properties are declared as follow
Properties are preceded by @property keyword. All properties are by default Thread-safe. nonatomic means that the access to the name property is not synchronized and hence not Thread-safe.
Properties are accessed using the dot[.] notation like <obj>.<property name>. Value can be set to a property as below
<obj>.<property name> = <value>
personObj.name = @”bharath”
What’s more important to this topic is the retain keyword which ensures that the values assigned to the name property are retained and hence acquires the ownership on that object.
Important thing to note is that the above two statements (assignment and accessor) will be replaced at compile time by its appropriate getter/setter methods
NSString *name = personObj.name;
is same as
NSString *name = [personObj name];
personObject.name = @”bharath”;
is same as
If you have a statement like @synthesize name in the Person Class implementation then, Objective C 2.0 compiler will automatically inserts the getter and setter methods into the compiled code
For a property name in Person class below
The getter and and setter methods will look like
[value retain]; // Since retain keyword is used in property declaration
So, invoking a statment
personObj.name = [[NSString alloc] initWithString:@”bharath”];
would have 2 retain count, one during alloc/init and one retained by the property.
So a better practice of assigning newly allocated instance to a property would be
NSString *myName = [[NSString alloc] initWithString:@”bharath”];
personObj.name = myName;
This topic may appear like a very basic thing, but still i see this mistake very often even sometimes from an experienced Cocoa programmers.
Happy Coding!! 🙂