2013-05-18 43 views
0

我正在使用一個使用JSON訂閱源的應用程序,但發現如果訂閱源不正確或缺少對象,它將導致我的應用程序崩潰。如何處理NSDictionary ObjectForKey JSON訂閱源錯誤崩潰

這是供我們接收目前,通常是當Web服務的合作,我們將獲得一個ID

result =  { 
     data =   { 
      result =    (
       "<null>" 
      ); 
     }; 
     success = 1; 
    }; 
}: 

我目前解析這樣

NSDictionary *results = [json objectForKeyOrNil:@"result"]; 
NSString *success = [results objectForKeyOrNil:@"success"]; 
NSDictionary *data = [results objectForKeyOrNil:@"data"]; 
NSDictionary *resultsArray = [data objectForKeyOrNil:@"result"]; 

最後我們進這樣做,試圖獲得丟失的物體

NSString *test = [dictionary objectForKeyOrNil:@"id"]; 

而在這一點上應用程序崩潰

我正在使用objectForKeyOrNil的類別類我希望能夠防止崩潰,但似乎無法正常工作。收到

- (id)objectForKeyOrNil:(id)key { 
    id val = [self objectForKey:key]; 
    if ([val isEqual:[NSNull null]]) { 
     return nil; 
    } 

    return val; 
} 

崩潰的消息 - [NSNull objectForKeyOrNil:]:無法識別的選擇發送到實例0x248e678

我想我會在這裏更新原來的職位有幾個人建議檢查ID,當我做到這一點仍然崩潰

NSDictionary *resultsArray = [data objectForKeyOrNil:@"result"]; 
// Loop through the downloaded data 
for (NSDictionary *dictionary in resultsArray) { 

    id val = [dictionary objectForKey:@"id"]; 
    if ([val isEqual:[NSNull null]] || val==nil) { 
    } 

    NSLog(@"Should be OK"); 

有了上面的代碼,它從來沒有達到的NSLog聲明

任何幫助非常感謝

感謝阿龍

回答

1

您應該測試你地圖之前,它是否等於[NSNull null]

+0

謝謝,我試過,但它仍然崩潰ID SERVERID = [dictionary objectForKey:@「id」]; if(serverID!= nil && [serverID class]!= [NSNull class]){ – MonkeyBlue

0

希望這會幫助你。

- (id)objectForKeyOrNil:(id)akey { 
    id object = [self objectForKey:aKey]; 
    if (object == nil) { 
     return @""; 
    } 
    if ([object isKindOfClass:[NSString class]) { 
     return object; 
    } else { 
     return nil; 
    } 
} 
2

你只需要檢查id是否爲null。或者您可以返回空白而不是零。那麼可能它不會崩潰

- (id)objectForKeyOrNil:(id)key { 
    id val = [self objectForKey:key]; 
    if (val ==[NSNull null]) 
    { 
     return nil; 
    } 
    return val; 
} 
-3

感謝所有我覺得其實我已經解決了這個問題,我想從其中didnt在冷杉的地方存在一個關鍵值的答覆。

將此代碼添加到檢查項中是否存在第一個幫助我捕獲錯誤:

if ([dictionary valueForKey:@"id"] != nil) { 
     NSLog(@"Key does not exist"); 
    } 

感謝所有幫助

亞倫

+3

這段代碼是無稽之談。首先,你應該使用objectForKey。 valueForKey與JSON數據完全不同並且非常危險。其次,你的測試當然是錯誤的。 !=無意味着存在。 ==零表示它不存在。 == [NSNull null]表示您的JSON文檔包含空值。 – gnasher729