2011-03-27 88 views
0

我很難搞清楚我做錯了什麼,所以我希望有人能夠指出我正確的方向。 我正在一個應用程序,你有一個對象的數組。這些對象中的每一個都可以有一個對象數組,因此(用於導航目的)有一個指向其主對象的指針。 當我試圖做一個這些對象的副本時,我遇到了內存泄漏。iphone copyWithZone內存泄漏 - 需要幫助

@interface ListItem : NSObject <NSCopying> { 

    ListItem *MasterItem; 
    NSString *strText; 
    NSMutableArray *listItems; 
    BOOL boolDone; 
    NSDate *itemDate; 

} 

@property (nonatomic, retain) ListItem *MasterItem; 

@property (nonatomic, retain) NSString *strText; 

@property (nonatomic, retain) NSMutableArray *listItems; 

@property (nonatomic, retain) NSDate *itemDate; 

@property BOOL boolDone; 

@end 


@implementation ListItem 
@synthesize strText, listItems, boolDone, MasterItem, itemDate; 

- (id) init 
{ 
    if (self = [super init]) 
    { 
     self.strText = nil; 

     self.listItems = nil; 

     self.itemDate = nil; 

     self.boolDone = FALSE; 

     self.MasterItem = nil; 
    } 
    return self; 

} 


-(id)copyWithZone:(NSZone *)zone 
{ 

    ListItem *another = [[[self class] allocWithZone:zone] init]; 

    another.MasterItem = [MasterItem copyWithZone:zone]; 
    another.listItems = [listItems copyWithZone:zone]; 
    another.strText = [strText copyWithZone:zone]; 
    another.itemDate = [itemDate copyWithZone:zone]; 
    another.boolDone = boolDone; 
    return another; 
} 


-(void) dealloc 
{ 
    if (itemDate != nil) 
     [itemDate release]; 

    if (MasterItem != nil) 
     [MasterItem release]; 

    if (strText != nil) 
     [strText release]; 

    if (listItems != nil) 
     [listItems release]; 

    [super dealloc]; 
} 


@end 
當我調用這個

,內存泄漏:

ListItem *itemMasterToSave = [itemMaster copy]; 
[itemMasterToSave release]; 
+0

看看SO如何讓MasterItem變成藍色?那是因爲它認爲它是一個類名。它應該是'masterItem'遵循約定。 – bbum 2011-03-27 17:20:27

回答

2

another.MasterItem = [MasterItem copyWithZone:zone]; 

應該

another.MasterItem = [[MasterItem copyWithZone:zone] autorelease]; 

和屬性設置的每一行。

此外,你忘了釋放NSDate屬性。

提示:您不需要執行無檢查,因爲它已經被客觀的c運行時所照顧。

+0

歡呼的伴侶。想要一個促銷代碼? .-) – Tom 2011-03-27 20:18:01