Properties Reading a writing variables can be complex. For example, setting an instance variable might look like this, The definition is this, Class * myObject; and the code is this. myObject = value; Several things deserve attention:
Declaring an instance variable as a property will make it available to the rest of the program, and the declaration allows you to set limits on the access. For example, you can declare it readonly and prevent any outside code from changing it.
Perhaps the most common property declaration is, @property (nonatomic, retain) Class * myObject; The effect of a property declaration is to create two method declarations, -(Class*) myObject;
-(void) setMyObject:(Class*) newValue;
These do not appear in the source code, but they are seen by the compiler. The first is the "getter" method. It has the name of the variable, unaltered. The second is the "setter", whose method name begins with "set" followed by the variable name with the first letter in upper case. If the declaration is "readonly" only the getter will be generated. No code is created, these are simply promises that code will be generated or written. The user can write the corresponding methods, but that is usually not done. Rather, the compiler will generate the methods when @synthesize is used. It is placed inside the implementation file. @synthesize myObject; This creates the code for the two accessor methods, and that code follows the rules given in the attributes of the @property declaration. As with @property you don't see this code, but the compiler does. Given a declaration like this, @property (nonatomic, retain) Class * myObject; The method "setMyObject" will be created. It will use nonatomic access, that is, no protection against multiple threads, and it will release the previous content of myObject and retain the new value. The code would effectively be, -(void)setMyObject:(Class *)newObj {
if (myObject != newObj) {
[myObject release];
myObject = [newObj retain];
}
}
A declaration like this, @property (nonatomic, copy) Class * myObject; would create something like this, -(void)setMyObject:(Class *)newObj {
Class * temp = [newObj copy];
[myObject release];
myObject = temp;
}
var = value;
self->var = value;
[self setVar:value];
self.var = value;
The latter two lines use the setter accessor. Since that method does not exist for a readonly variable they will fail because the compiler will be unable to link to the method. In these examples we have identified a property with a specific instance variable. If you write your own accessors, you can make properties that depend on the values of several variables or change several variables. See the chapter on Declared Properties in Apple's "The Objective C Programming Language". The page was last updated
Tuesday, March 27, 2012 3:15 PM
|