我想从我的项目的plist文件中获取应该排序的数据。现在我的plist看起来像
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>code</key>
<string>AF</string>
<key>phone_code</key>
<string>93</string>
<key>name</key>
<string>Afghanistan</string>
</dict>
<dict>
<key>code</key>
<string>AL</string>
<key>phone_code</key>
<string>355</string>
<key>name</key>
<string>Albania</string>
</dict>
等等到最后一个国家。我正在获取这样的数据
NSString* path = [[NSBundle mainBundle] pathForResource:@"CountriesWithPhoneCodes" ofType:@"plist"];
NSArray* a = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *d in a)
{
NSString *cdate = [d objectForKey:@"CDate"];
if ([cdate isEqualToString:@"Whatever is currently selected"])
{
NSString *text = [d objectForKey:@"Text"];
// do something with text here
}
}
NSDictionary *dict = [[NSDictionary alloc]init];
dict = [self indexKeyedDictionaryFromArray:a];
NSLog(@"This is %@",[[dict allValues]objectAtIndex:0]);
我得到的输出是
This is {
code = AF;
name = Afghanistan;
"phone_code" = 93;
}
我无法正常访问数据。如何创建一个字典,其中phone_code为值和国家/地区名称作为键。
答案 0 :(得分:1)
NSPredicate
完全符合您的需求。
NSString *path = [[NSBundle mainBundle] pathForResource:@"CountriesWithPhoneCodes" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"phone_code = %@", @"String variable containing code"];
NSDictionary *countryDictionary = [array filteredArrayWithPredicate:predicate].firstObject;
如果您想使用此类结构创建字典:{"phone_code":"country_code"}
:
NSMutableDictionary *phonesDict = [NSMutableDictionary new];
for (NSDictionary *dict in array) {
NSString *phoneCode = dict[@"phone_code"];
NSString *countryCode = dict[@"country_code"];
phonesDict[countryCode] = phoneCode;
}
注意:您应该将此字典存储在某处以避免访问磁盘上的文件。
答案 1 :(得分:0)
NSDictionary *dictRoot = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
// Your dictionary contains an array of dictionary
// Now pull an Array out of it.
NSArray *arrayList = [NSArray arrayWithArray:[dictRoot objectForKey:@"catlist"]];
// Now a loop through Array to fetch single Item from catList which is Dictionary
[arrayList enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) {
// Fetch Single Item
// Here obj will return a dictionary
NSLog(@"Category name : %@",[obj valueForKey:@"category_name"]);
NSLog(@"Category id : %@",[obj valueForKey:@"cid"]);
}];