2012-08-01 2 views
0
을 처리 할 수 ​​

I는 다음과 같다 몇 가지 코드가 있습니다NSJSONSerialization는 null 값

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"]]; 

는 null가 아닌 경우 확인하거나가있는 NSString * is_private 변수에 전무을 넣을 수 있도록이 문제를 해결할 수있는 방법이 있나요?

감사합니다.

답변

1

문제는 NSJSONSerialization과 아무 관련이 없으며 nil 값을 stringWithString:으로 전달한다는 점과 관련이 있습니다. 단순히 그 라인을 NSString *is_private = [dict objectForKey:@"is_private"];으로 보내는 것이 어떨까요?

또한 NSString을 사용하여 부울 값을 저장하는 이유는 무엇입니까? NSNumber이 훨씬 더 적합합니다.

+0

가있어! 예를 들어 stringWithString을 보았을 때 많은주의를 기울이지 않았습니다. 그게 거기에 있다는 의미는 무엇입니까? 감사! StackOverflow를 사용하면 대답을 받아 들일 것입니다. – GeekedOut

+0

아주 솔직히 말하면, 나는 그것을 사용한 적이 없다. 당신은 확실히이 질문을 할 첫 번째되지 않습니다 :) http://stackoverflow.com/questions/1616348/nsstring-stringwithstring-whats-the-point – oltman

1

stringWithString:에 전달하기 전에 [dict objectForKey:@"is_private"]nil 또는 [NSNull null]인지 확인하는 것이 어떨까요?

2

당신은 너무처럼 처리 할 수 ​​있어야합니다 :

id value = [dict valueForKey:@"is_private"]; 
NSString *is_private = [value isEqual:[NSNull null]] ? nil : value;