按NSDictionary的key來對其進行排序:
先將dict的allkeys賦給一個數(shù)組属划,然后通過sortedArrayUsingComparator:方法對數(shù)組排序曙砂,然后遍歷數(shù)組取字典對應(yīng)key的值就ok
NSArray?*keys = [dict?allKeys];
NSArray?*sortedArray = [keys?sortedArrayUsingComparator:^NSComparisonResult(idobj1,?id?obj2) {
return?[obj1?compare:obj2?options:NSNumericSearch];
}];
for?(NSString?*categoryId?in?sortedArray) {
??
NSLog(@"[dict objectForKey:categoryId] === %@",[dictobjectForKey:categoryId]);
}
優(yōu)化結(jié)果:
//對字典中的值進行排序
keys = [dict3keysSortedByValueUsingSelector:@selector(compare:)];
for(NSString*sinkeys)
{
NSLog(@"%@ = %@", s, dict3[s]);
}
方法二:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"students" ofType:@"plist"];
NSDictionary *stuDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
self.studentIndexArray = [NSMutableArray arrayWithCapacity:1];
NSArray *arr = [[stuDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
字典遍歷:
//遍歷
NSEnumerator*e = [dict3objectEnumerator];//枚舉器值遍歷
while(str = [enextObject])
{
NSLog(@"%@", str);
}
e = [dict3keyEnumerator];//枚舉器關(guān)鍵字遍歷
while(str = [enextObject])
{
NSLog(@"%@", str);
}
for(NSString*keyindict3)//快速遍歷
{
NSLog(@"%@=%@", key, dict3[key]);
}
//字典的文件讀寫方法
[dict3writeToFile:@"/Users/#####/Desktop/dict.plist"atomically:YES];
NSDictionary*dict6 = [NSDictionarydictionaryWithContentsOfFile:@"/Users/######/Desktop/dict.plist"];
NSLog(@"%@", dict6);