2012-01-12 63 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

相关问题