面试总结(四)实现有序字典
实现方法
- 按NSDictionary的key来对其进行排序:
- 将字典的Value再放到一个字典里面,key分别使用有序的字符串
- 先将字典转模型,再放到数组里面
- 先将dict的allkeys赋给一个数组,然后通过sortedArrayUsingComparator:方法对数组排序,然后遍历数组取字典对应key的值就ok
这里只说大概的两张方法的实现
方法一
1 NSArray *keys = [dict allKeys]; 2 NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(idobj1, id obj2) { 3 return [obj1 compare:obj2 options:NSNumericSearch]; 4 }]; 5 for (NSString *categoryId in sortedArray) { 6 …… 7 NSLog(@"[dict objectForKey:categoryId] === %@",[dictobjectForKey:categoryId]); 8 }
方法二:
1 NSString *filePath = [[NSBundle mainBundle]pathForResource:@"students" ofType:@"plist"]; 2 NSDictionary *stuDic = [NSDictionary dictionaryWithContentsOfFile:filePath]; 3 self.studentIndexArray = [NSMutableArray arrayWithCapacity:1]; 4 NSArray *arr = [[stuDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
时间: 2024-10-27 18:09:10