1. There are often some variables in the class that require set and get operations, and OC provides convenient attribute @property to replace the set and get methods, which reduces the frequent and simple duplication of code. The following code:
@interface Person : NSObject
@property NSString* strName;
@property int nAge;
@end
@implementation Person
@synthesize strName;
@synthesize nAge;
@end
By adding a @property before the class declaration variable, this variable is an attribute variable @property nsstring* strName, which is added in the class implementation @synthesize let Xcode generate compiled code for you @synthesize strName. In fact, the Xcode compiler will automatically add the set and get methods for this property at compile time, as strname in the example above adds methods Setstrname and strname to the class, and we can set and access strname through the method. But the convenient way is to access it through.
@autoreleasepool {
// insert code here...
Person* p = [[Person alloc] init];
p.strName = @"52xpz";
p.nAge = 16;
NSLog(@"name:%@, age:%d", p.strName, p.nAge);
NSLog(@"name:%@, age:%d", [p strName], [p nAge]);
[p setStrName:@"akon"];
[p setNAge:18];
NSLog(@"name:%@, age:%d", p.strName, p.nAge);
NSLog(@"name:%@, age:%d", [p strName], [p nAge]);
}
[email protected] There are options such as copy (copy), retain (reserved), readonly (read-only), ReadWrite (read/write), Nonatomic (no atomic session access), assign (simply assigned value).
The default property is the Assgin and nonatomic options . The following code declares that strname is copy, Readwrite;eye is retain, ReadWrite, nonatomic. Convenient Ah!
@interface Person : NSObject
@property (copy, readwrite) NSString* strName;
@property int nAge;
@property (retain, readwrite, nonatomic) Eye* eye;
@end
How do we not let the compiler generate property code for us instead of using our own code? Answer @dynamic keyword.
@interface Person : NSObject
@property (readonly) int nAge;
@end
@implementation Person
@dynamic nAge;
-(int) nAge
{
return 10;
}
@end
3. About attribute selection Personally, there are a few principles:
1) Set and get as long as a parameter set the variable with the property, there are two and above parameter setting variables should not be used.
2) code is simply to set and get variables should use attributes, reduce the amount of code while the code is simple, good readability.
OBJECTIVE-C Basic 5: Attribute @property