@property 是OC中可以快速定义一个属性的关键字,以下咱们定义一个属性。objective-c
@property NSString *String;
这样咱们就可使用这个属性安全
// // Created by chao on 15/8/29. // Copyright (c) 2015 ___FULLUSERNAME___. All rights reserved. // #import <Foundation/Foundation.h> @interface Person : NSObject{ NSString *firstName; NSString *lastName; } - (void)setFirstName:(NSString *)first; - (NSString *)firstName; - (void)setLastName:(NSString *)last; - (NSString *)lastName; @end //在.m文件里实现 #import "Person.h" @implementation Person { } - (void)setFirstName:(NSString *)first { firstName = [first copy]; } - (NSString *)firstName { return firstName; } - (void)setLastName:(NSString *)last { lastName = [last copy]; } - (NSString *)lastName { return lastName; } @end
如今有了@property
只要简单的声明一下就可让编译器替咱们作以上哪些繁杂的工做。多线程
@property NSStrinng *firstNmae; @property NSString *lastName;
编译器会自动在属性名以前添加下划线,一次做为实例变量的名字,在上面的声明中会生成两个实例变量
_firstNam, _lastName.咱们也可使用@synthesize语法指定实例变量的名字。app
@synthesize firstName = _myFirstName; //使用指定的实例变量名称 @synthesize lastName = _myLastName;//若是没有特殊须要尽可能使用系统默认的名称
@property NSStrinng *firstNmae; @property NSStrinng *firstNmae; @dynamic firstName, lastname; //编译器不会自动为这两个属性合成存取方法,或实例变量。
在为以上类添加一个只读的ID和weight属性。性能
@property (readonly) NSInteger ID; @property (readwrite) NSInteger height;
若是咱们这程序中试图修改person 的ID属性编译器就会报错优化
生命周期类型的特性包括, assign, strong, weak和copy 这些特性决定了存方法如何处理与其相关的内存管理问题atom
@property (assign) NSInteger ID; 这段代码等同于实现了一下存方法 - (void)setID:(NSInteger)d { ID = d; }
看了不少博客讲解的copy都只是简单的说了一下,copy特性要求拷贝传入对象。并无进行深刻的讲解,好比为何要copy传入对象,下面我写一下我本身对copy的理解线程
@property (strong) NSString *firstName; @property (copy) NSString *lastName; NSMutableString *name = [[NSMutable alloc] initWithString:@"Li"]; [person setFirstNmae:name]; [person setLastName:name];//这样修改name 不会对实例变量产生影响。 //看如下程序的输出 NSMutableString *firstName = [NSMutableString stringWithString:@"Zhang"]; NSMutableString *lastName = [NSMutableString stringWithString:@"San"]; person.firstName = firstName; person.lastName = lastName; NSLog(@"修改前的 :%@%@", person.firstName, person.lastName); [firstName appendString:@"fe"]; [lastName appendString:@"aefa"]; NSLog(@"修改后的 :%@%@", person.firstName, person.lastName); NSLog(@"%@%@", firstName, lastName);
2.若是传入的对象是不可修改的,copy方法实际是在调用copyWithZone:通常咱们自定义的对象若是要求copy,应该重写 copyWithZone:方法从而优化copy过程code
- (id)copyWithZond { return self; }