OC基础--关键字@property 和 @synthesize

不打扰是莪最后的温柔 提交于 2020-01-02 00:44:10

一、@property关键字需要掌握的知识:

1.用在@interface中,用来自动生成setter和getter的声明

例:@property int age;--相当于执行了右边的代码-->-(void) setAge:(int) age;  -(int) age;

二、@synthesize关键字需要掌握的知识:

1.用在@implementation中,用来自动生成setter和getter的实现

例:@synthesize age = _age;

2.注意:在  @synthesize age = _age;  中如果没有指定成员变量名,实现中默认访问的就是同名的成员变量

例: @synthesize age;//默认访问的就是age成员变量,而不是_age成员变量

如果age这个成员变量不存在,程序会在@implementation中自动生成一个私有的age变量

同理,如果指定的成员变量也不存在,程序也会在@implementation中自动生成一个私有的跟指定变量同名的成员变量

三、Xcode版本注意事项:

1.Xcode 4.4前:关键字@property 只是自动生成set方法和get方法的声明

2.Xcode 4.4后:关键字@property 将会自动生成set方法和get方法的声明和实现、增加一个_开头的成员变量

四、代码实例:

#import <Foundation/Foundation.h>

@interface Car : NSObject
{
    int _wheels;
    //int _speed;
}
@property int wheels;
@property int speed;
@end

@implementation Car
// 默认会访问wheels成员变量,如果这个成员变量不存在,自动生成一个私有的wheels变量
@synthesize wheels;

// setter和getter会访问_speed成员变量,如果这个成员变量不存在,自动生成一个私有的_speed变量
@synthesize speed = _speed;

- (NSString *)description
{
    return [NSString stringWithFormat:@"wheels=%d,_speed=%d", wheels, _speed];
}

@end

int main()
{
    Car *c = [[Car alloc] init];
    
    c.wheels = 4;
    c.speed = 250;

    
    NSLog(@"%@", c);
    //NSLog(@"轮子个数:%d", c.wheels);
    
    return 0;
}

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!