我有一个方法应该采用 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'