将对象添加到NSMutableArray时无法识别的select器

我有一个NSMutableArray属性,我想要添加对象和删除对象的单身类。 出于某种原因,我得到:

-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x1edf24c0 

当试图添加到它的exception。 以下是单例界面的相关代码:

 //outbox item is the type of objects to be held in the dictionary @interface OutboxItem : NSObject @property (nonatomic, assign) unsigned long long size; @end @interface GlobalData : NSObject @property (nonatomic, copy) NSMutableDictionary *p_outbox; + (GlobalData*)sharedGlobalData; @end 

单身人士的实施:

 @implementation GlobalData @synthesize p_outbox; static GlobalData *sharedGlobalData = nil; + (GlobalData*)sharedGlobalData { if (sharedGlobalData == nil) { sharedGlobalData = [[super allocWithZone:NULL] init]; sharedGlobalData.p_outbox = [[NSMutableDictionary alloc] init]; } return sharedGlobalData; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedGlobalData == nil) { sharedGlobalData = [super allocWithZone:zone]; return sharedGlobalData; } } return nil; } - (id)copyWithZone:(NSZone *)zone { return self; } @end 

这里是引发exception的代码:

 GlobalData* glblData=[GlobalData sharedGlobalData] ; OutboxItem* oItem = [OutboxItem alloc]; oItem.size = ...;//some number here [glblData.p_outbox setObject:oItem forKey:...];//some NSString for a key 

我错过了一些非常明显的事情?

你的

 @property (nonatomic, copy) NSMutableDictionary *p_outbox; 

正在创build一个你分配给它的对象的副本。 当你为它分配一个NSMutableDictionary时,它会创build一个NSMutableDictionary对象的副本,它是NSDictionary ,它不是一个可变副本。

所以改变它

对于非ARC

 @property (nonatomic, retain) NSMutableDictionary *p_outbox; 

对于ARC

 @property (nonatomic, strong) NSMutableDictionary *p_outbox; 

问题在于你的财产:

 @property (nonatomic, copy) NSMutableDictionary *p_outbox; 

该属性的copy语义会导致在为该属性分配值时所创build的字典的副本。 但是字典的copy方法总是返回一个不可变的NSDictionary ,即使在NSMutableDictionary上调用也是如此。

要解决这个问题,你必须为属性创build你自己的setter方法:

 // I'm a little unclear what the actual name of the method will be. // It's unusual to use underscores in property names. CamelCase is the standard. - (void)setP_outbox:(NSMutableDictionary *)dictionary { p_outbox = [dictionary mutableCopy]; }