2016-07-16 90 views
0

我有一個NSArray(「address_components」)的多個NSDictionary。每個NSDictionary包含NSString值的一個NSArray(「類型」)。像這樣..在NSArray(iOS)中查找包含特定值的NSDictionary

"address_components" =   (
{ 
    "long_name" = "Perumbavoor Puthencruz Road"; 
    "short_name" = "Perumbavoor Puthencruz Rd"; 
    types =     (
     route 
    ); 
}, 
{ 
    "long_name" = Vengola; 
    "short_name" = Vengola; 
    types =     (
     locality, 
     political 
    ); 
}, 
{ 
    "long_name" = Ernakulam; 
    "short_name" = EKM; 
    types =     (
     "administrative_area_level_2", 
     political 
    ); 
}, 
{ 
    "long_name" = Kerala; 
    "short_name" = KL; 
    types =     (
     "administrative_area_level_1", 
     political 
    ); 
}, 
{ 
    "long_name" = India; 
    "short_name" = IN; 
    types =     (
     country, 
     political 
    ); 
}, 
{ 
    "long_name" = 683556; 
    "short_name" = 683556; 
    types =     (
     "postal_code" 
    ); 
} 
); 

如何獲得包含字符串「locality」的數組的字典。在這個例子中,我想要得到的字典..

{ 
    "long_name" = Vengola; 
    "short_name" = Vengola; 
    types =(
     locality, 
     political 
    ); 
} 

謝謝:)

+0

檢查我的答案。 –

回答

2

您需要predicate地址這樣的陣列

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY types CONTAINS[c] %@", @"locality"]; 
NSArray *arr = [yourArray filteredArrayUsingPredicate:predicate]; 
+0

謝謝。這工作完美:) –

+0

歡迎隊友,快樂編碼:) –

0

您可以檢查數組包含字典或BOT:

for(int i=0; i<[arr count];i++){ 
if([arr[i] isKindOfClass:[NSDictionary Class]]){ 
NSDictionary *dic=arr[i]; 
NSLog("%@",dic); 
} 
} 
2

使用此代碼

NSArray *myArray = [yourAddressDict valueForKey:"address_components"]; 


NSMutableArray *NewArray = [NSMutableArray array]; 

    for (NSDictionary *ob in myArray) { 
     NSArray *arraylocality = [ob valueForKey:@"types"]; 
     BOOL isthere= [arraylocality containsObject:@"locality"]; 
     if (isthere) { 
      [NewArray addObject:ob]; 
     } 

    } 

NSLog(@"%@",NewArray); 
0

這裏亞去:

NSArray *list = @[ 
       @{ 
        @"long_name" : @"Perumbavoor Puthencruz Road", 
        @"short_name" : @"Perumbavoor Puthencruz Rd", 
        @"types" : @[@"route"] 
        }, 
       @{ 
        @"long_name" : @"Vengola", 
        @"short_name" : @"Vengola", 
        @"types" : @[@"locality", @"political"] 
        }, 
       @{ 
        @"long_name" : @"Ernakulam", 
        @"short_name" : @"EKM", 
        @"types" :     @[ 
          @"administrative_area_level_2", 
          @"political"] 
        } 
       ]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.types CONTAINS 'locality'"]; 
NSArray *result = [list filteredArrayUsingPredicate:predicate]; 
NSLog(@"result: %@", result); 

結果:

{ 
     "long_name" = Vengola; 
     "short_name" = Vengola; 
     types =   (
      locality, 
      political 
     ); 
    } 
相關問題