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

来源:互联网 发布:windows 映射 编辑:程序博客网 时间:2024/06/07 06:26

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

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编译器感叹,如此方便和好用的工具我真心是第一次见,默默的赞一下。

3 0
原创粉丝点击