Objective-C:当我添加NSInictionary时,静态NSDictionary会抛出NSInvalidArgumentException

时间:2013-07-29 04:28:20

标签: objective-c nsmutabledictionary

我有一个方法应该使用NSManagedObject,将其属性复制到字典中,然后将字典添加到NSMutableArray中的NSMutableArray中,并使用NSManagedObjectID键。问题是当我尝试添加到静态NSMutableDictionary时崩溃,只有当我在现场制作时才会崩溃。

问题肯定与静态NSMutableDictionary更改有关,因为如果我使用非静态字典,我不会得到异常。它的定义如下(@implementation上面):

static NSMutableDictionary* changes = nil;

以下是方法:

+ (void)acceptChange: (NSManagedObject *)change{
if (!changes){
    NSLog(@"Making new changes dicitonary"); //it prints this when I run
    changes = [[NSDictionary alloc] init];
}
NSManagedObjectID* objectID = change.objectID;
NSMutableArray* changeArray = [changes objectForKey: objectID];
bool arrayDidNotExist = NO;
if (!changeArray){
    changeArray = [[NSMutableArray alloc] init];
    arrayDidNotExist = YES;
}
[changeArray addObject: [(this class's name) copyEventDictionary: change]]; //copies the NSManagedObject's attributes to an NSDictionary, assumedly works
if (arrayDidNotExist) [changes setObject: changeArray forKey: objectID];//throws the  exception

//If I do the exact same line as above but do it to an [[NSMutableDictionary alloc] init] instead of the static dictionary changes, it does not throw an exception.

if (arrayDidNotExist) NSLog(@"New array created");
NSLog(@"changeArray count: %d", changeArray.count);
NSLog(@"changes dictionary count: %d", changes.count);

}

确切的异常消息是:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0xa788e30'

3 个答案:

答案 0 :(得分:1)

使用NSMutableDictionary代替NSDictionary。你得到例外是因为, NSMutableDictionary可以动态修改,NSDictionary不能。

NSMutableDictionaryNSDictionary的子类。因此NSDictionary的所有方法都可以通过NSMutableDictionary对象访问。此外,NSMutableDictionary还添加了动态修改内容的补充方法,例如方法setObject:forKey:

修改

您已使用NSDictionary而不是`NSMutableDictionary。

初始化它
if (!changes){
    NSLog(@"Making new changes dicitonary"); //it prints this when I run
    //changes = [[NSDictionary alloc] init]; 
                ^^^^^^^^^^^^^^ ------------------> Change this. 
    changes = [[NSMutableDictionary alloc] init];
}

答案 1 :(得分:1)

[__NSDictionaryI setObject:forKey:]表明您的词典是不可变的。您实际上是在将字典初始化为不可变的。这就是它在添加对象时引发异常的原因。

此处更改此行:

if (!changes){
   ....
    changes = [[NSDictionary alloc] init];
}

为:

if (!changes){
    ....
    changes = [[NSMutableDictionary alloc] init];
}

答案 2 :(得分:1)

您声明您的字典是NSMutableDictionary,因此在编译时您的字典是NSMutable字典,但在运行时它是NSDictionary,因为您将其分配为NSDictionary,您无法对其进行更改,因此例外。请将字典定义为: -

changes = [[NSMutableDictionary alloc] init];

如果您阅读了例外情况的说明,那就说明了同样的事情。

希望这有帮助。