2012-03-27 43 views
0

在我TaggingScreen.m初始化函数,我做的 -iOS的 - 无法删除内存泄漏

tags = [myTagMgr getMyTags]; 

在我getMyTags的方法,我做以下 -

NSMutableDictionary *myTags = [NSMutableDictionary new]; 
.... 
return myTags; 

我得到了内存泄漏对于这种方法中的myTags。我应该在哪里释放内存? “标签”是整个TaggingScreen类中使用的属性。因此,如果我执行autorelease,当我尝试访问该类的其他方法中的标记时,会收到一条异常,指出“发送到释放实例的消息”。

编辑:

- (NSMutableDictionary *)getMyTags 
{ 

NSMutableDictionary *myTags=[NSMutableDictionary new]; 
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init]autorelease]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tag" 
           inManagedObjectContext:localObjectContext]; 
[fetchRequest setEntity:entity]; 

NSError *error = nil; 
NSArray *fetchedArrayObjects = [localObjectContext executeFetchRequest:fetchRequest error:&error]; 

if (fetchedArrayObjects ==nil) { 
    return nil; 
} 
if ([fetchedArrayObjects count]==0) { 
    return nil; 
} 

Tag *aMessage; 
for (int i=0; i<[fetchedArrayObjects count];i++) 
{ 
    aMessage= (Tag *)[fetchedArrayObjects objectAtIndex:(NSUInteger)i]; 

    [myTags setValue:[aMessage isSet] forKey:[aMessage tagName]]; 
    } 
return myTags; 
} 
+0

什么样的@属性是'tags'? – yuji 2012-03-27 16:09:22

+0

它的一个@property(nonatomic,assign)NSMutableDictionary *标签; – Suchi 2012-03-27 16:14:02

回答

1

维涅什和VIN的解决方案是正确的,但根据你所说的,做的最好的事情是改变tagsstrong属性:

@property (nonatomic, strong) NSMutableDictionary *tags; 

除非你在一个情况下是可能会出现保留循环(例如,委托对象),您应该使用strong,以便您的属性不会从您的属性释放。

另外,除非你使用ARC,你要自动释放myTags

return [myTags autorelease]; 

哦,如果你不使用ARC,你要确保释放tagsdealloc

+0

对不起,也许我错了,但是如果你使用ARC,你不能调用autorelease。 – 2012-03-27 16:25:20

+0

你说得对,我会提到的。但是如果OP使用ARC,他们会忽略分配给弱财产的警告。 – yuji 2012-03-27 16:28:07

+0

没问题yuji。 – 2012-03-27 16:31:27

0

尝试:

return [myTags autorelease]; 
0

应该在方法autorelease。如果你需要它,你将不得不在retain它叫你的地方。

tags = [[myTagMgr getMyTags] retain]; 
1

,如果你在init方法做它,你可以做到以下几点:

tags = [[myTagMgr getMyTags] retain]; 

,而不是在你的getMyTags方法

return [myTags autorelease]; 

通过这种方式,你有+1为您NSDictionary和您可以在控制器中使用self.tags进行访问。

其中

@property (nonatomic, retain) NSDictionary* tags; 

记住释放它在dealloc

- (void)dealloc 
{ 
    [tags release]; tags = nil; 
    [super dealloc]; 
} 

附:我假设你不使用ARC。