我正在做我的項目在xcode 4.2(舊版本)。對於我的應用程序,我只需將dto類中的變量,數組設置爲在整個應用程序生命週期中使用。所以我設置了這樣的屬性。管理目標c中的內存
AppDTO(子類NSObject中的)
AppDTO.h
@property(nonatomic,retain)anotherAppDTO *aAppDTO;
@property(nonatomic,retain)NSMutableArray *array1;
@property(nonatomic,retain)NSMutableArray *array2;
@property(nonatomic,retain)NSString *string1,*string2,*string3;
AppDTO.m
- (id)init
{
self = [super init];
if (self) {
self.aAppDTO = [[anotherAppDTO alloc]init];
self.array1 = [[NSMutableArray alloc]init];
self.array2 = [[NSMutableArray alloc]init];
self.string1 = @"Hello";
self.string2= @"Hai";
}
}
-(void)dealloc
{
if(array1 != nil)
{
[array1 release];
array1 = nil;
}
if(array2 != nil)
{
[array2 release];
array2 = nil;
}
[aAppDTO release];
aAppDTO = nil;
[super dealloc];
}
當我分析我的應用程序在Xcode 4.3.2,我得到內存警告在self.array1和self.array2(在線上分配的對象上的潛在泄漏...),但是當我將self.array1更改爲array1時,警告消失。
使用自我的原因是什麼。如果我將@property(nonatomic,retain)設置爲變量(如array1,array2,string1,string2),我需要使用self嗎?
另外在dealloc方法中,我聽說我們不想使用[self.array1 release],相反我們可以使用[array1 release]。這是對的嗎?
我是否需要在dealloc方法中釋放我的字符串。
另外我在dealloc方法中發佈aAppDTO。如果我在另一個AppDTO類中分配一些對象,當我調用[aAppDTO release]方法時它會自動釋放。
任何人都可以澄清我。
self.array1 = [[NSMutableArray alloc]init];
是一樣的:
[self setArray1: [[NSMutableArray alloc]init]];
正如你可以看到你是不是分配
非常感謝, 阿尼什
不需要在'dealloc'中檢查'nil';只是「釋放」對象。另外,'NSString'屬性幾乎總是'copy'而不是'retain'。如果這是一個新項目,您應該使用** ARC **。 – bbum 2012-08-12 14:25:59