开发者

iphone copyWithZone memory leak - need help

开发者 https://www.devze.com 2023-02-19 21:05 出处:网络
I am having a hard time figuring out what I a开发者_开发技巧m doing wrong, so I hope someone is able to point me in the right direction.

I am having a hard time figuring out what I a开发者_开发技巧m doing wrong, so I hope someone is able to point me in the right direction. I am working on an App where you have a array of objects. each of these objects can have a array of objects and therefore (for navigation purpose) have a pointer to its master object. when i am trying to do a copy of one of these objects i am experiencing a memory leak.

@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

when i am calling this, the memory leaks:

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


The line

another.MasterItem = [MasterItem copyWithZone:zone];

should be

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

and for every lines of property setting.

Also, you forgot to release NSDate property.

Tips: you do not need to do nil checking because it's taken care by objective c runtime already.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号