我從服務器的以下消息:存取權限JSON從服務器端
{"_license":false}
當我試圖從那裏_license
擺脫它顯示null
。我試過這樣:
NSString *items = [[parser objectWithString:[request responseString] error:nil] valueForKey:@"_license"];
NSLog(@"response server%@", items);
任何想法爲什麼?以及如何解決?
我從服務器的以下消息:存取權限JSON從服務器端
{"_license":false}
當我試圖從那裏_license
擺脫它顯示null
。我試過這樣:
NSString *items = [[parser objectWithString:[request responseString] error:nil] valueForKey:@"_license"];
NSLog(@"response server%@", items);
任何想法爲什麼?以及如何解決?
嘗試連接灑了你的代碼,不要做每一件事的一條線。然後檢查變量是否包含正確的值。
NSLog(@"Server response: %@",[request responseString]);
NSError * error = nil;
NSDictionary *response = [parser objectWithString:[request responseString] error:&error]
if (!response)({
NSLog(@"Error parsing JSON: %@", error);
return;
}
NSLog(@"Dictionary: %@", response);
NSNumber *hasValidLicense = [response objectForKey:@"_license"];
NSLog(@"Has valid license: %@", hasValidLicense);
if ([hasValidLicense boolValue]){
//Yes we have a valid license.
} else {
// No valid license.
}
請注意,在Cocoa Touch錯誤處理中,[錯誤輸出參數只能在方法返回值爲'nil'或'NO']時讀取(http://developer.apple.com/library/ios/#documentation /Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html)。首先應該檢查返回值,然後檢查錯誤輸出參數。 – 2011-11-18 10:08:38
@Bavarious我編輯了我的答案。文檔鏈接非常有用。 – rckoenes
用以下內容替換你的行:
BOOL items = [[[parser objectWithString:[request responseString] error:nil] valueForKey:@"_license"] boolValue];
如果'-boolValue'之前的表達式是'nil',那麼您的答案不能解決問題。它總是將'NO'分配給'items'。 – 2011-11-18 10:09:27
確認'[request responseString]'包含您期望的字符串。檢查'-objectWithString:'的返回值。如果它是'nil',則檢查錯誤輸出參數(並傳遞一個有效的地址而不是'nil')。另外,爲什麼不使用' - [NSDictionary objectForKey:]',這是規範的方法來讀取字典項目? – 2011-11-18 09:55:58