【问题标题】:iphone copyWithZone memory leak - need helpiphone copyWithZone 内存泄漏 - 需要帮助
【发布时间】:2011-03-27 12:23:56
【问题描述】:

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

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

【问题讨论】:

  • 看看 SO 是如何让MasterItem 变成蓝色的?那是因为它认为它是一个类名。按照惯例应该是masterItem

标签: iphone objective-c memory-leaks


【解决方案1】:

线

another.MasterItem = [MasterItem copyWithZone:zone];

应该是

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

并为每一行属性设置。

另外,您忘记释放 NSDate 属性。

提示:你不需要做 nil 检查,因为它已经被目标 c 运行时处理了。

【讨论】:

    猜你喜欢
    • 2011-03-27
    • 2011-03-28
    • 2020-10-11
    • 2012-07-15
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多