首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iphone copyWithZone内存泄漏-需要帮助

iphone copyWithZone内存泄漏-需要帮助
EN

Stack Overflow用户
提问于 2011-03-27 20:23:57
回答 1查看 1.3K关注 0票数 1

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

代码语言:javascript
复制
@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

当我调用它时,内存泄漏:

代码语言:javascript
复制
ListItem *itemMasterToSave = [itemMaster copy];
[itemMasterToSave release];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-27 21:58:31

这条线

代码语言:javascript
复制
another.MasterItem = [MasterItem copyWithZone:zone];

应该是

代码语言:javascript
复制
another.MasterItem = [[MasterItem copyWithZone:zone] autorelease];

以及属性设置的每一行。

此外,您还忘了释放NSDate属性。

小贴士:你不需要做空检查,因为它已经由objective c运行时处理了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5449181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档