2011-03-27 90 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