所以我设置此方法来检索我的用户默认值。它应该检查密钥是否包含任何内容。如果没有,则返回nil。如果是,则返回该对象。很简单吧?无论如何,如果物体不存在,它会崩溃。它也没有通过这种方法。如果对象是nil,它将继续进入if语句ANYWAYS并在其评论的位置崩溃。我不明白为什么它继续进入if语句而不是跳到其他地方并继续前进。但是,如果对象存在于默认值中,则应用程序可以正常运行。任何想法?
+ (PAUserObject *)fetchDataSetWithDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id data = [defaults objectForKey:kPAUserDefaultsStorage];
// at ^^^ this point, data is nil (as it should be)
NSLog(@"MY KEY - %@", data);
// ^^^ Still (correctly) nil
if([defaults objectForKey:kPAUserDefaultsStorage]){ // <--- This should return nil, since it printed as nil in the last 2 statements
NSData *thisData = [[NSUserDefaults standardUserDefaults] objectForKey:kPAUserDefaultsStorage]; // <--- What the %$#@? it entered the if statement anyways?
NSLog(@"Encoded Array - %@", thisData);
PAUserObject *userObject = [NSKeyedUnarchiver unarchiveObjectWithData:thisData]; // <--- CRASH
NSLog(@"decoding data");
return userObject;
} else { // <--- DOESNT EVEN REACH THIS CODE!!! WTF
return nil;
}
}
调试步骤
我放置了断点并检查了变量值,直到崩溃为止。就我所知,这绝对是它崩溃的路线
错误消息:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
答案 0 :(得分:0)
因此,您的错误很明显:您无法将nil
对象传递给该函数。
但是,我复制了你的代码......并道歉,但它正常运作 ..
#define kPAUserDefaultsStorage @"key"
+ (NSString *)fetchDataSetWithDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id data = [defaults objectForKey:kPAUserDefaultsStorage];
// at ^^^ this point, data is nil (as it should be)
NSLog(@"MY KEY - %@", data);
// ^^^ Still (correctly) nil
if([defaults objectForKey:kPAUserDefaultsStorage]){ // <--- This should return nil, since it printed as nil in the last 2 statements
NSData *thisData = [[NSUserDefaults standardUserDefaults] objectForKey:kPAUserDefaultsStorage]; // <--- What the %$#@? it entered the if statement anyways?
NSLog(@"Encoded Array - %@", thisData);
// <--- CRASH
NSLog(@"decoding data");
return @"IS NOT NIL";
} else { // <--- DOESNT EVEN REACH THIS CODE!!! WTF
return @"IS NIL";
}
}
从这里打来:
NSLog(@"%@", [[self class] fetchDataSetWithDefaults]);
控制台日志:
2014-05-26 23:32:36.450 Test[11540:60b] MY KEY - (null)
2014-05-26 23:32:44.886 Test[11540:60b] IS NIL