@property,@synthesize是objective-c用来自动生成数据成员的getter和setter方法的
@property在interface部分声明了数据成员的getter和setter方法,而@synthesize在implementation部分使编译器自动定义getter和setter方法。
例子:
//.h文件
#import <Foundation/Foundation.h>
@interface Employee : NSObject
{
int employeeNumber;
NSString *name;
Employee *supervisor;
int salary;
}
@property (nonatomic, readonly) int employeeNumber;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) Employee *supervisor;
@property (nonatomic, assign) int salary;
...
@end
//实现:
#import "Employee.h"
@implementation Employee
@synthesize employeeNumber;
@synthesize name; //使编译器实现name 和setName:方法
@synthesize supervisor;
@synthesize salary;
...
@end
注:如果不在implementation中使用@synthesize,那么编译器默认使用@dynamic,即用户自己提供setter和getter方法的实现。如果既使用了@synthesize,又提供了自己的实现,那么编译器会选择用户自己提供的实现。
@property
声明格式:@property (attributes ) type name
attributes有以下几种:
1)assign,retain,copy:定义了setter的方式。
assign(默认):简单的复制 myProperty = newValue; 用于基本数据类型(非object对象)
retain:如果需要保持对象的一致,那么使用retain
copy: 对象必须是可复制的,即实现了copyWithZone。如果只是想获取对象的当前值或状态,那么使用copy就行了。
2)读写权限:readwrite,readonly。
readonly不是想setter
3)nonatomic,(默认为atomic)
如果声明为nonatomic,那么就不是线程安全的
atomic使用lock来保证线程安全,这会牺牲一定的性能。因此如果该property不是用于多线程的,那么就声明为nonatomic。
===================================================
可以修改setter和getter的名字。setter和getter的默认名字为:setMyProperty: ,myProperty。
如: @property (nonatomic, getter=isChanged) BOOL changed;
一般用于Boolean类型的属性,增加可读性。
======================================================
如何让一个property拥有setter实现,但是对外不可见,而对内可见:
@interface Employee : NSObject
{
NSString* name;
}
@property (nonatomic, readwrite) employeeNumber;
@property (nonatomic, readwrite) name; //在属性列表中没有声明
@end
----------
@implementation Employee
@synthesize name;
@synthesize employeeNumber;
employeeNumber有setter和getter方法,setter方法对内可见,但是对外不可见。
注:虽然不可见,但是仍然能够被调用。
============================================
objective-c2.0提供了dot语法来使用一个属性
Employee *employee = // ...
int currentSalary = employee.salary;
employee.salary = 1000000;
注:如果是用retain和copy方式声明的成员,记得在dealloc中释放。