Tho*_*son 11 iphone objective-c nsdictionary nsarray
基本上我有一个带键和值的NSDictionary.
键都是数字,但目前它们是字符串.
我希望能够将它们作为数字进行比较,以便对它们进行排序.
例如:如果我有这样的词典:
{
"100" => (id)object,
"20" => (id)object,
"10" => (id)object,
"1000" => (id)object,
}
Run Code Online (Sandbox Code Playgroud)
我希望能够像这样对它进行排序:
{
"10" => (id)object,
"20" => (id)object,
"100" => (id)object,
"1000" => (id)object,
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
谢谢
汤姆
zou*_*oul 14
不确定你要做什么 - 词典本质上是未排序的,默认实现中没有稳定的键排序.如果要按排序键遍历值,可以执行以下操作:
NSInteger floatSort(id num1, id num2, void *context)
{
float v1 = [num1 floatValue];
float v2 = [num2 floatValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
NSArray *allKeys = [aDictionary allKeys];
NSArray *sortedKeys = [allKeys sortedArrayUsingFunction:floatSort context:NULL];
for (id key in sortedKeys)
id val = [aDictionary objectForKey:key];
…
Run Code Online (Sandbox Code Playgroud)
您无法对字典进行排序,但您可以将键作为数组获取,对其进行排序,然后按该顺序输出.sortedArrayUsingComparator将执行此操作,您可以将字符串与NSNumericSearch选项进行比较.
NSArray* keys = [myDict allKeys];
NSArray* sortedArray = [keys sortedArrayUsingComparator:^(id a, id b) {
return [a compare:b options:NSNumericSearch];
}];
for( NSString* aStr in sortedArray ) {
NSLog( @"%@ has key %@", [myDict objectForKey:aStr], aStr );
}
Run Code Online (Sandbox Code Playgroud)