iphone copyWithZone内存泄漏 - 需要帮助

时间:2011-03-27 12:23:57

标签: iphone objective-c memory-leaks

我很难弄清楚我做错了什么,所以我希望有人能指出我正确的方向。 我正在一个应用程序,你有一个对象数组。这些对象中的每一个都可以有一个对象数组,因此(出于导航目的)有一个指向其主对象的指针。 当我试图复制其中一个对象时,我遇到了内存泄漏。

@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];

1 个答案:

答案 0 :(得分:2)

该行

another.MasterItem = [MasterItem copyWithZone:zone];

应该是

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

并为每一行属性设置。

此外,您忘记发布NSDate属性。

提示:您不需要进行零检查,因为它已经由目标c运行时处理。

相关问题