Objective C / NSMutableDictionary - [NSCFSet objectForKey:]:无法识别的选择器

时间:2011-03-27 19:01:24

标签: objective-c exception nsmutabledictionary

我不明白我做错了什么。我有一个字典作为单例类的属性:

@interface CABResourceManager : NSObject
{
.... 
    NSMutableDictionary* soundMap;
}
@property (retain) NSMutableDictionary *soundMap;

然后我在一个类方法中向这个字典添加一个对象:

+ (void)loadSoundFromInfo:(ABSoundInfo)sound
{
    static unsigned int currentSoundID = 0;
    CABSound* newSound = [[CABSound alloc] initWithInfo:(ABSoundInfo)sound soundID:++currentSoundID];
    [[CABResourceManager sharedResMgr].soundMap setObject:newSound forKey:sound.name];
}

尝试用另一种方法获取它:

+ (ALuint)playSoundByName:(NSString*)name
{
    NSMutableDictionary* map = [CABResourceManager sharedResMgr].soundMap;
    CABSound *sound = [map objectForKey:name];   // here comes the exception

并且应用程序退出异常。

2011-03-27 20:46:53.943 Book3HD-EN[5485:207] *** -[NSCFSet objectForKey:]: unrecognized selector sent to instance 0x226950
2011-03-27 20:46:53.945 Book3HD-EN[5485:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException'

我想它可能有一些内存管理,但是对我来说看起来很清楚:CABSound对象通过setObject()保留在字典中,此时不应该被释放。

2 个答案:

答案 0 :(得分:1)

我会检查soundMap是否已正确初始化。看起来soundMap在您收到错误时是一个错误的指针。它可能恰好是+ loadSoundFromInfo中的nil,它不会立即产生错误。

答案 1 :(得分:0)

确保您已在指定的初始值设定项中初始化了soundMap:

// - (id) init... or something else
soundMap = [[NSMutableDictionary alloc] init];

不要忘记覆盖默认的dealloc实现:

// class implementation file
- (void)dealloc {
  [soundMap release];
  //...release other objects you own...
  [super dealloc];
}