1

我有一个带有 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

我错过了一些非常明显的东西吗?

4

2 回答 2

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];
}
于 2013-03-12T16:38:32.020 回答
2

您的

@property (nonatomic, copy) NSMutableDictionary *p_outbox;

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

所以改成

对于非 ARC

@property (nonatomic, retain) NSMutableDictionary *p_outbox;

对于弧

@property (nonatomic, strong) NSMutableDictionary *p_outbox;
于 2013-03-12T16:38:52.797 回答