2

我有一些看起来像这样的代码:

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                     options:kNilOptions
                                                       error:&error];

NSArray *arrRequests = [NSJSONSerialization JSONObjectWithData:data
                                                       options:NSJSONReadingMutableContainers
                                                         error:nil];

// Loop through the array and generate the necessary annotation views
for (int i = 0; i<= arrRequests.count - 1; i++)
{
    //now let's dig out each and every json object
    NSDictionary *dict = [arrRequests objectAtIndex:i];

    NSString *is_private = [NSString
                            stringWithString:[dict objectForKey:@"is_private"]];
                            ...

它在 is_private 的值为 1 或 0 时起作用,但如果它为 null,则会在此行出现异常并崩溃:

NSString *is_private = [NSString stringWithString:[dict objectForKey:@"is_private"]];

有没有办法检查它是否不为空或处理它以便能够将 nil 放入 NSString *is_private 变量中?

谢谢!

4

3 回答 3

3

您应该能够像这样处理它:

id value = [dict valueForKey:@"is_private"];
NSString *is_private = [value isEqual:[NSNull null]] ? nil : value;
于 2012-08-01T16:24:47.903 回答
1

你为什么不只是检查是否[dict objectForKey:@"is_private"]nil[NSNull null]在传递给它之前stringWithString:

于 2012-08-01T16:24:19.677 回答
1

您的问题与NSJSONSerialization您将nil值传递给stringWithString:. 为什么不只是简单地那行来NSString *is_private = [dict objectForKey:@"is_private"];

另外,为什么要使用 anNSString来存储布尔值?安NSNumber会更适合。

于 2012-08-01T16:24:28.307 回答