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

时间:2013-03-12 16:33:04

标签: ios objective-c nsmutabledictionary

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

-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x1edf24c0
尝试添加时出现

异常。以下是单例接口的相关代码:

//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

这是抛出异常的代码:

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

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

2 个答案:

答案 0 :(得分:3)

问题在于你的财产:

@property (nonatomic, copy) NSMutableDictionary *p_outbox;

属性的copy语义导致在为属性赋值时生成的字典副本。但是,即使在copy上调用,字典的NSDictionary方法也始终返回不可变NSMutableDictionary

要解决此问题,您必须为属性创建自己的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];
}

答案 1 :(得分:2)

你的

@property (nonatomic, copy) NSMutableDictionary *p_outbox;

正在创建您分配给它的该对象的副本。 当您为其分配NSMutableDictionary时,它会创建NSMutableDictionary对象的副本,NSDictionary不是可变副本。

所以将其改为

非ARC

@property (nonatomic, retain) NSMutableDictionary *p_outbox;

对于ARC

@property (nonatomic, strong) NSMutableDictionary *p_outbox;