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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容