IOS 字典排序 遍历 字典的文件读写方法

按NSDictionary的key来对其进行排序:

先将dict的allkeys赋给一个数组,然后通过sortedArrayUsingComparator:方法对数组排序,然后遍历数组取字典对应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]);

}

优化结果:

//对字典中的值进行排序

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];//枚举器关键字遍历

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);

你可能感兴趣的:(IOS 字典排序 遍历 字典的文件读写方法)