In objective-C, @ property is used to identify attributes (generally instance variables ). Use @ synthesize in the implementation file to identify the declared variables, so that the system can automatically generate the setting and obtaining methods.
That is to say, the @ property and @ synthesize pairs allow the system to automatically generate the setting and obtaining methods.
Example:
Test. h
# Import <Foundation/Foundation. h> @ Interface Test: nsobject {int intx; int inty ;}@ property int intx, inty;-(void) print; @ end
Test. m
# Import "test. H "@ implementation test @ synthesize intx, inty;-(void) print {nslog (@" intx + inty = % d ", intx + inty);} @ end
Classtest. m
# Import <Foundation/Foundation. h> # import "test. H "int main (INT argc, const char * argv []) {ngutoreleasepool * Pool = [[ngutoreleasepool alloc] init]; test * test = [[test alloc] init]; [Test setintx: 1]; [test setinty: 1]; [test print]; [test release]; [pool drain]; return 0 ;}
ProgramRunning result:
Intx + inty = 2
Obviously, there are no methods in the test class definition and class implementation: setintx and setinty, but we can use these two methods to set values for the instance variables of the class during program writing, this is the result of @ property and @ synthesize.
This is the simplest use of @ property and @ synthesize.
In addition ". "Operation (vertex operator), using this operator can easily access attributes (or member variables in the vertex class can be very convenient, a bit like the taste of C/C ++ ), because, the preceding settings can also be written in the following form:
Test. intx = 1; test. inty = 1;
It is equivalent:
[Test setintx: 1]; [test setinty: 1];
Note the following:"." Operations (vertex operators) can only be used in setter and getter methods, but cannot be used in other methods of the class.
(Most of the books use vertex operators for introduction. The principle is here)
@ Property has many other attributes. @ Property and synthesize enable the system to automatically generate the setting method and obtain the method. What is the method automatically generated by the system? What are the rules? Next we will introduce it.