Objective-c features

Source: Internet
Author: User

@ 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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.