retain\copy属性的内存管理的应用说明

在前面
http://www.cnblogs.com/GoGoagg/archive/2011/09/02/2163781.html
http://www.cnblogs.com/GoGoagg/archive/2011/08/25/2152879.html
两篇都说了下内存管理的问题,没有实践的代码。这里弄一个


原则:
在init函数中,使用.属性方式来为属性初始化
在dealloc函数中,使用->成员变量方式来释放。或直接使用.属性=nil来释放。

1、非对象类型,如int,使用属性和成员变量都无问题
2、对象类型,如NSString ,NSDate等,如无readonly的限定,使用.属性来初始化。如果有readonly的限定,用成员变量来处理。注意,要注意类方法分配的方式。

声明:

@interface MyClass:NSObject
@property (nonatomic ,retain) NSDate *RateDate;
@property (nonatomic ,retain) NSString *Error;
@end


A

@implement MyClass
@synthesize RateDate;
@synthesize Error;

-(id) init
{
self = [super init];
if (self) {
self.RateDate = [NSDate date];
self.Error = nil;
}
}

-(void) dealloc
{
if (self.RateDate)
[self->RateDate release];
if (self.Error)
[self->Error release];
[super dealloc];
}
@end



B

@implement MyClass
@synthesize RateDate;
@synthesize Error;

-(id) init
{
self = [super init];
if (self) {
self.RateDate = [NSDate date];
self.NSString = nil;
}
}

-(void) dealloc
{
self.RateDate = nil;
self.Error = nil;
[super dealloc];
}
@end



C【会出现释放异常】

@implement MyClass
@synthesize RateDate;
@synthesize Error;

-(id) init
{
self = [super init];
if (self) {
self->RateDate=[NSDate date];//问题在于此类方法属于自动释放。如果要使用的话:[[NSDate alloc] init];
self->Error = [NSString alloc] init];
}
}

-(void) dealloc
{
if (self.RateDate)
[self->RateDate release];
if (self.Error)
[self->Error release];
[super dealloc];
}
@end


个人建议:
采用B这种方式处理

根据实际结合AB实践方式来处理属性的内存问题


原文地址:https://www.cnblogs.com/GoGoagg/p/2207091.html