@ Property: Pre-compiled commands automatically declare the setter and getter methods of attributes.
Sometimes you need to declare the corresponding instance variables
When do I need to declare instance variables?
Let's look at the following example:
@interface Foo: NSObject@property t;@@implmentation Foo- (NSInteger)t{ ...}- (void)setT:(NSInteger)newT{ ...}@end
How can we implement the corresponding setter and getter methods? The @ systhesize automatic merging is not used here
If so
-(Void) setT :( NSInteger) newT
{
Self. t = newT;
}
Then this function will recursively call itself until the stack overflows. Because self. t is used to tell the compiler to use the accessors to access the name. If
Bare name. The compiler will assume that we have directly modified the instance variable.
Back to this question, how can we implement the above setter? Obviously, an instance variable must be defined here.
The above code is changed:
@interface Foo : NSObject{ NSInteger t;}@property NSInteger t;@end@implementation Foo-(void)setT:(NSInteger)newt{ t = newt;}-(NSInteger)t{ return t;}@end
Must the instance variable name be consistent with the attribute name? The answer is no.
To avoid obfuscation, we usually define it as follows:
@interface Foo : NSObject{ NSInteger _t;}@property NSInteger t;@end@implementation Foo@synthesize t=_t;-(void)setT:(NSInteger)newt{ _t = newt;}-(NSInteger)t{ return _t;}@end
In this way, we can use instance variables to access the class. In other words, we can use @ brief hesize to control the generated setter and which instance variables the getter method works.
@ Brief hesize t = _ t1;
@ Brief hesize t = _ t2;