Objective-C基础笔记(2)@property和@synthesize

先贴出使用@property和@synthesize实现的上一篇中的代码,再解释这两个keyword的使用方法和含义,代码例如以下:

Person.h文件

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    int _age;  //能够被子类訪问
    //这里系统会帮我们生成一个默认的 int _no 私有变量(不能被子类訪问)
}

@property int age;
@property int no;

//自己写一个构造方法
- (id)initWithAge:(int)age andNo:(int)no;

@end
Person.m文件

#import "Person.h"

@implementation Person

//Xcode 4.5以上都不用写以下两句(可省略,而且默认是_age和_no)
//@synthesize age = _age; //声明为protected
//@synthesize no = _no; //默认生成的是私有的

- (id)initWithAge:(int)age andNo:(int)no {
    if(self = [super init]){
        _age = age;
        _no = no;
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"age is %i and no is %i", _age, _no];
}

@end
main.m文件

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] initWithAge:15 andNo:2];
        
        NSLog(@"age is %i and no is %i", person.age, person.no);
        
        [person setNo:3];
        NSLog(@"no is %i", [person no]);
        //%@代表打印一个OC对象
        NSLog(@"%@", person);
    }
    return 0;
}
输出结果:

2014-11-12 21:53:15.406 firstOCProj[826:47802] age is 15 and no is 2

2014-11-12 21:53:15.407 firstOCProj[826:47802] no is 3

2014-11-12 21:53:15.408 firstOCProj[826:47802] age is 15 and no is 3

能够看到上面的代码简洁了不少,@property的作用就等价于对成员变量的声明,@synthesize的作用就等价于对成员变量setter和getter的标准实现。

须要注意的是:

1、在Xcode4.5以上能够不用写@synthesize属性(编译器默认加入)。

2、这样的写法能够和前面的写法(旧的写法)交叉使用。

3、假设要对setter或者getter方法有特殊处理。能够使用旧的写法(编译器就不会默认帮我们实现)。

4、假设没有显式的声明变量,则默认生成一个私有成员变量(不能被子类使用,如上面的_no)。

以下我们将上面代码该的更简单一些:

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
@property int no;

@end
Person.m

#import "Person.h"

@implementation Person

@end
main.m

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [Person new];
        [person setAge:20];
        [person setNo:3];
        NSLog(@"age is %i and no is %i", person.age, person.no);
    }
    return 0;
}
输出结果:

2014-11-12 22:14:44.002 firstOCProj[849:52867] age is 20 and no is 3

注意:我的编译器Xcode是4.5以上的。所以能省略Person.m中的@synthesize属性。

这里不得不正确OC和Xcode编译器感叹。如此方便和好用的工具我真心是第一次见,默默的赞一下。

posted @ 2016-02-20 16:27  lcchuguo  阅读(244)  评论(0编辑  收藏  举报