我很难找出我做错了什么,所以我希望有人能给我指出正确的方向。我在一个应用程序上工作,其中你有一个对象数组。这些对象中的每一个都可以有一个对象数组,因此(为了导航目的)有一个指向它的主对象的指针。当我试图复制其中一个对象时,我遇到了内存泄漏。
@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];发布于 2011-03-27 21:58:31
这条线
another.MasterItem = [MasterItem copyWithZone:zone];应该是
another.MasterItem = [[MasterItem copyWithZone:zone] autorelease];以及属性设置的每一行。
此外,您还忘了释放NSDate属性。
小贴士:你不需要做空检查,因为它已经由objective c运行时处理了。
https://stackoverflow.com/questions/5449181
复制相似问题