[英]Objective-C throws NSInvalidArgumentException with Dictionaries & Arrays
[英]Objective-C: Static NSDictionary throws NSInvalidArgumentException when I add to it
我有一种方法,应该采用NSManagedObject,将其属性复制到字典中,然后将字典添加到具有NSManagedObjectID键的静态NSMutableDictionary中的NSMutableArray。 问题是,当我尝试添加到静态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'
使用NSMutableDictionary
而不是NSDictionary
。 您正在获得例外,因为, NSMutableDictionary可以动态修改,而NSDictionary无法。 。
NSMutableDictionary
是NSDictionary
子类。 因此,可以通过NSMutableDictionary
对象访问NSDictionary
所有方法。 此外, NSMutableDictionary
还添加了补充方法来动态修改事物,例如setObject:forKey:
方法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];
}
[__NSDictionaryI setObject:forKey:]
显示您的字典是不可变的。 您实际上是将字典初始化为不可变的。 这就是为什么它在添加对象时引发异常的原因。
在这里更改此行:
if (!changes){
....
changes = [[NSDictionary alloc] init];
}
至:
if (!changes){
....
changes = [[NSMutableDictionary alloc] init];
}
您已将字典声明为NSMutableDictionary,因此在编译时,该字典为NSMutable字典,但是在运行时,它是NSDictionary,因为您将其分配为NSDictionary,无法对其进行更改,因此是例外。 请将字典定义为:-
更改= [[NSMutableDictionary分配]初始化];
如果您阅读了有关异常的说明,则说明的是同一件事。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.