2012-03-27 42 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。