码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-02-03 16:36:36      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

一、@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;
}

  

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

标签:

原文地址:http://www.cnblogs.com/gchlcc/p/5179956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!