2013-04-25 89 views
1

我的json響應如下。如何將選定的ID與數組中的國家ID進行比較並顯示其名稱不是ID

{ 
    "continent_code" = EU; 
    "country_code" = al; 
    "country_id" = 2; 
    "country_name" = Albania; 
}, 
{ 
    "continent_code" = AF; 
    "country_code" = dz; 
    "country_id" = 3; 
    "country_name" = Algeria; 
}, 

我的代碼是這樣的。

country_selected=2; 
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:@"Response"]; 
    for(NSDictionary *countname in wholeJsonArray) 
    { 

     /* 
     NSString *cName = [NSString stringWithFormat:@"%@",[countname  
     objectForKey:@"country_name"]]; 
     [countryArray addObject:cName]; 
     */ 


     NSString *countryName = [countname objectForKey:@"country_name"]; 
     if(countryName) 
      [countryArray addObject:countryName]; 


     NSString *stateName=[countname objectForKey:@"state_name"]; 
     if(stateName) 
      [stateArray addObject:stateName]; 
    } 

    for(NSDictionary *cid in wholeJsonArray) 
    { 

     NSNumber *number = [cid objectForKey:@"country_id"]; 
     if(number) 
      [idcountry addObject:number]; 

     NSNumber *statenumber=[cid objectForKey:@"state_id"]; 
     if(statenumber) 
      [idstate addObject:statenumber]; 

    } 
} 

我的問題是,如果用戶選擇的國家ID 2然後比較在陣列字段這個值,然後在標題標籤顯示是阿爾巴尼亞。

那麼我該怎麼做這個輸出?

請幫幫我。

在此先感謝。

回答

0

創建找國家從選擇countryID

- (NSDictionary *)countryWithId:(NSUInteger)countryID 
{ 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"country_id == %d",countryID]; 
    return [[self.wholeJSONArray filteredArrayUsingPredicate:predicate]lastObject]; 

} 

您可以獲取國家像

NSDictionary *country = [self countryWithId:2]; 
NSString *countryName = country[@"country_name"]; 

編輯的方法:或

country_selected=2; 
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:@"Response"]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"country_id == %d",countryID]; 
NSDictionary *country = [[wholeJsonArray filteredArrayUsingPredicate:predicate]lastObject]; 
NSString *countryName = country[@"country_name"]; 
1
country_selected=2; 
NSString *countryName; 
for(NSDictionary *countname in wholeJsonArray) 
{ 
    NSNumber *country_id = [countname objectForKey:@"country_id"]; 
    if(country_selected == country_id.integerValue){ 
     countryName = [countname objectForKey:@"country_name"]; 
    }   
} 

其中countryName將包含選定的國家/地區名稱;

+0

非常感謝你 – 2013-04-25 06:15:51

相關問題