2012-01-12 64 views
0

我有一個簡單的問題。這是我的頭文件:存儲UIImageViews在NSMutableDictionary

#import <UIKit/UIKit.h> 

@interface FirstFaceController : UIViewController 

@property (nonatomic,retain) NSMutableDictionary *face1Layers; 

@end 

這.M,在這裏我初始化我的字典,並把其中的UIImageView:

#import "FirstFaceController.h" 

@implementation FirstFaceController 

@synthesize face1Layers; 



-(void) dealloc { 
    [face1Layers release]; 
    [super dealloc]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.face1Layers = [NSMutableDictionary dictionary]; 
    [self.face1Layers setObject: 
      [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]] 
       forKey:@"pic"]; 

    [self.view addSubview:[self.face1Layers objectForKey:@"pic"]]; 
    if ([[face1Layers objectForKey:@"pic"] superview] == nil) { 
     //.... 
    } 
} 

然後我打電話[[face1Layers objectForKey:@"pic"]上海華]我有 「EXC_BAD_ACCESS」。 爲什麼?

+0

試試這個... self.face1Layers = [[NSMutableDictionary alloc] init]; – 2012-01-12 13:20:27

+1

你是如何創建'self.view'的? – vikingosegundo 2012-01-12 13:29:08

+0

我不太確定你想用if語句來檢查。如果你調用'[self.view addSubview:[self.face1Layers objectForKey:@「pic」]];'然後'[self.face1Layers objectForKey:@「pic」]'將始終有一個超級視圖,除非'self.view'確實不存在。 – FelixLam 2012-01-12 13:33:49

回答

1

嘗試這樣做:

NSMutableDictionary* tempDict = [[NSMutableDictionary alloc] init]; 
self.face1Layers = tempDict; 
UIImageView* picView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]]; 
[self.face1Layers setObject:picView forKey:@"pic"]; 
[picView release]; 
[tempDict release]; 

不要創建並插入你NSMutableDictionaryUIImageView的throught一行代碼,因爲你有泄漏。

在第一種情況下,如果您執行以下操作,則保留計數爲2。 face1Layers有保留政策。

self.face1Layers = [[NSMutableDictionary alloc] init]; 

可避免這種分裂代碼,我以前解釋或發送autorelease消息給初始化的對象。

在第二種情況下,當您在NSDictionaryNSArray(及其子類)中添加對象時,這些類將保留添加的對象。

希望它有幫助。

+1

這也創建了一個泄漏,因爲屬性保留了mutableDictionary:'self.face1Layers = [[[[[[NSMutableDictionary alloc] init] autorelease];' – FelixLam 2012-01-12 13:30:30

+0

謝謝。我已經修好了。 – 2012-01-12 13:31:21

+1

,並且此代碼正在泄漏'face1Layers',因爲 - 由於保留屬性 - 它的保留計數爲2. self'face1Layers = [NSMutableDictionary字典]行;'沒問題。 – vikingosegundo 2012-01-12 13:32:41

0

嗯,我認爲有幾件事情錯在這裏:

  1. 你永遠不分配字典中的NSMutableDictionary的alloc初始化
  2. 的UIImageView的分配,但從來沒有公佈。我將其設置爲對象之前分配,然後將其添加,然後鬆開
+1

OP正在通過屬性立即保留自動釋放字典。行'self.face1Layers = [NSMutableDictionary dictionary];'沒問題。 – vikingosegundo 2012-01-12 13:34:52

+0

哦真的嗎?您不再需要alloc init,然後使用self。?我不知道 – 2012-01-12 14:25:10

+0

[NSMutableDictionary dictionary]是[[[[NSMutableDictionary alloc] init] autorelease]的一個便捷方法。它返回一個自動釋放對象,如果你的屬性有retain屬性,屬性將保留該對象。 – FelixLam 2012-01-12 14:58:28

相關問題