您的位置:首页 > 移动开发 > Objective-C

Objective-C中的@property,@synthesize和点语法

2013-06-10 18:47 288 查看

1.普通的设置器和访问器

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

@interface Person : NSObject{
int identify;
int age;
}

- (void)setIdentify:(int) identify;  //设置器
- (int)identify;                     //访问器
- (void)printInfo;
@end
Person.m

#import "Person.h"

@implementation Person

- (void)setIdentify:(int) _identify{  //设置器
identify = _identify;
}
- (int)identify{                      //访问器

return identify;
}
- (void)printInfo{                    //打印identify
NSLog(@"Person identify is: %d",identify);
}
@end
Main.m
#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[])
{

@autoreleasepool {

// insert code here...
NSLog(@"Hello, World!");
Person *person = [[Person alloc] init];
[person setIdentify:100];
NSLog(@"Person identify: %d",[person identify]);

}
return 0;
}


2. 使用@property和@synthesize来简化设置器和访问器

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

@interface Person : NSObject{
int identify;
int age;
}

@property(nonatomic) int identify;
@end
Person.m
#import "Person.h"

@implementation Person
@synthesize identify = _identify;
@end


在@property()括号中,可以填写的属性有:

readwrite:默认,便是属性是可读写的,也就是说可以使用getter和setter
readonly: 只读,意味着没有set方法,只能使用getter
assign: 默认,引用计数不增加
retain: 引用计数增加1
原子性: actomic 默认
非原子性:nonatomic,表示不用考虑线程安全问题

assign(缺省),retain,copy是属性如何存储;

atomic是oc中的一种线程保护技术,是防止在未完成的时候,被另外一个线程使用,造成数据错误;
@synthesize是合成的意思,就是编译器自动实现getter和setter函数。

3. 点语法

self.identify = 1; //设置器 相当于[person setIdentify:1]; 调用setIdentify方法
self.identify; //访问器 相当于[person identify]; 调用identify方法

点语法是编译器级别
项目中如果想用点语法,必须在项目中的.h文件和.m文件中声明和实现 setIdentify和 identify方法,也就是说要声明和实现getter和setter方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: