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常に immutable を返します。NSDictionaryNSMutableDictionary

この問題を解決するには、プロパティに対して独自のセッター メソッドを作成する必要があります。

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

割り当てたオブジェクトのコピーを作成しています。を割り当てると、変更可能なコピーではないオブジェクトNSMutableDictionaryのコピーが作成されます。NSMutableDictionaryNSDictionary

だからそれを

非ARC用

@property (nonatomic, retain) NSMutableDictionary *p_outbox;

アークの場合

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