2012-04-09 117 views
3

所以我解析一個twitter的時間表。在JSON響應中有一個名爲「following」的字段。它應該是真的或假的。如何檢查數組中的值是否不爲NULL?

但有時候該字段丟失。

當我這樣做:

NSLog(@"%@", [[[timeline objectAtIndex:i] objectForKey:@"user"] objectForKey:@"following"]); 

這是輸出:

1 
1 
0 
0 
1 
<null> 
1 
1 

那麼如何檢查這些值?

回答

13

NSArray和其他集合不能將nil作爲值,因爲nil是集合結束時的「標記值」。您可以使用以下命令查找對象是否爲空:

if (myObject == [NSNull null]) { 
    // do something because the object is null 
} 
+0

我們也可以檢查數組。 – 2013-06-26 06:36:37

3

如果字段丟失,NSDictionary -objectForKey:將返回一個零指針。您可以測試這樣的零指針:

NSNumber *following = [[[timeline objectAtIndex:i] objectForKey:@"user"] objectForKey:@"following"]; 

if (following) 
{ 
    NSLog(@"%@", following); 
} 
else 
{ 
    // handle no following field 
    NSLog(@"No following field"); 
} 
-1

這並不是說是空的時間表元素。它可以是「用戶」字典或空的「跟隨」對象。我建議創建一個用戶模型類來封裝一些json/dictionary混亂。事實上,我敢打賭,你可以找到適用於iOS的開源Twitter API。

無論哪種方式,您的代碼將更具可讀性,就像這樣:

TwitterResponse *response = [[TwitterResponse alloc] initWithDictionary:[timeline objectAtIndex:i]]; 
NSLog(@"%@", response.user.following); 

上述TwitterResponse將實現一個只讀屬性TwitterUser *user這又將實現NSNumber *following。使用NSNumber,因爲它會允許空值(JSON響應中的空字符串)。

希望這能幫助你走上正軌。祝你好運!

-1

檢查數組包含空值使用此代碼。

if ([array objectAtIndex:0] == [NSNull null]) 
{ 
//do something 
} 
else 
{ 
}