标签:
在MRC模式下,我们建一个Person类的对象.h文件如下
1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject 4 @property (nonatomic, retain)NSString *name; 5 @property (nonatomic, retain)NSString *sex; 6 @property (nonatomic, assign)NSInteger age; 7 //自定义初始化 8 -(instancetype)initWithName:(NSString *)name Sex:(NSString *)sex Age:(NSInteger)age; 9 //便利构造器 10 11 +(instancetype)personWithName:(NSString *)name Sex:(NSString *)sex Age:(NSInteger)age; 12 13 @end
.m文件如下
#import "Person.h" @implementation Person //在MRC下,如果需要同时重写setter和getter方法,必须下面的的语句 @synthesize name = _name; //自定义初始化 -(instancetype)initWithName:(NSString *)name Sex:(NSString *)sex Age:(NSInteger)age { if (self = [super init]) { _name = name; _sex = sex; _age = age; } return self; } //便利构造器 +(instancetype)personWithName:(NSString *)name Sex:(NSString *)sex Age:(NSInteger)age { return [[[Person alloc] initWithName:name Sex:sex Age:age]autorelease]; } //重写dealloc可以验证对象内存空间是否被收回,方式是否被调用 -(void)dealloc { NSLog(@"这个对象被销毁"); //以后只要在MRC中,重写dealloc方法,就需要一一对应为语义特征为retain或者copy的属性生成的实例变量release一次 [self.name release];//针对sertter方法最后一次retain的release [_sex release]; [super dealloc]; } //MRC下,retain的内部实现 setter方法 //-(void)setName:(NSString *)name //{ // if (_name != name) { // [_name release]; // _name = [name retain]; // } //} //-(NSString *)name //{ // return [[_name retain]autorelease]; //} -(void)setName:(NSString *)name { if (_name != name) { [_name release]; _name = [name copy]; } } -(NSString *)name { return [[_name retain]autorelease]; } @end
在MRC模式下,copy与retain的setter,getter方法写法一致,但是实现的机制不相同,前者是得到传入参数的副本,重新开辟空间,而后者是使引用计数加一
标签:
原文地址:http://www.cnblogs.com/DevinSMR/p/5142874.html