' NSInvalidArgumentException',原因:' *** setObjectForKey:对象不能为nil(key:device_uid)'

时间:2015-12-02 09:30:32

标签: ios objective-c crash ios8.4

尝试在iPhone上运行应用程序时出错。我不明白为什么在这种情况下我有一个零错误

>    Terminating app due to uncaught exception 'NSInvalidArgumentException',<br/>
>    reason: '  setObjectForKey: object cannot be nil (key: device_id)'<br/>
>    First throw call stack:<br/>
    (0x183ce0f48 0x19918bf80 0x183bcc4e0 0x10006f5f0 0x1002b9ca8 0x1002b9c68 0x1002bf710 0x183c981f8 0x183c96060 0x183bc4ca0 0x18f148088 0x1892dcffc 0x1000716a0 0x1999ce8b8)<br/>
    libc++abi.dylib: terminating with uncaught exception of type NSException

Here is the part of    appdelegate.m file concerned by this error :

// Get the users Device Model, Display Name, Token & Version Number
UIDevice *device = [UIDevice currentDevice];

NSUserDefaults *dict = [NSUserDefaults standardUserDefaults];
NSString *identifier = [dict stringForKey:@"identifier"];
NSString *deviceName = device.name;
NSString *deviceModel = device.model;
NSString *deviceSystemVersion = device.systemVersion;

// Prepare the Device Token for Registration (remove spaces and < >)
NSString *deviceToken = [[[[token description]
                           stringByReplacingOccurrencesOfString:@"<"withString:@""]
                          stringByReplacingOccurrencesOfString:@">" withString:@""]
                         stringByReplacingOccurrencesOfString: @" " withString: @""];

NSMutableDictionary *postDatas = [NSMutableDictionary dictionary];
[postDatas setObject:appName forKey:@"app_name"];
[postDatas setObject:appVersion forKey:@"app_version"];
[postDatas setObject:identifier forKey:@"device_uid"];
[postDatas setObject:deviceToken forKey:@"device_token"];
[postDatas setObject:deviceName forKey:@"device_name"];
[postDatas setObject:deviceModel forKey:@"device_model"];
[postDatas setObject:deviceSystemVersion forKey:@"device_version"];
[postDatas setObject:pushBadge forKey:@"push_badge"];
[postDatas setObject:pushAlert forKey:@"push_alert"];
[postDatas setObject:pushSound forKey:@"push_sound"];

Request *request = [Request alloc];
request.delegate = self;

[request postDatas:postDatas withUrl:@"push/iphone/registerdevice/"];

这个方法已被弃用吗?

2 个答案:

答案 0 :(得分:5)

您在标识符中获得nil。所以请像这样检查

NSString *identifier = [dict stringForKey:@"identifier"];

if([identifier length] != 0)
    [postDatas setObject:identifier forKey:@"device_uid"];
else
    [postDatas setObject:@"" forKey:@"device_uid"];

答案 1 :(得分:1)

您不能将nil值放入字典中。它会崩溃。

你真正需要调查的是:这些零值是从哪里来的,当你得到零值时,适当的做法是什么?这是你唯一可以决定的事情。 Mukesh的答案应该是如何存储空字符串而不是nil。这可以避免崩溃。 经常是正确的事情,但并非总是如此。因此,如果其中一个值为nil,请调查您的应用应该执行的操作,并使其完全相同。