使用字典键对可变数组进行排序

时间:2011-01-29 18:05:47

标签: objective-c arrays sorting dictionary mutable

我正在尝试使用单个键(“dayCounter”)创建一个简单的可变数组,我打算用它进行排序。我已经在网上阅读了大量的例子,但没有快乐。

所以我创建了这个数组。注意第一个条目是NSDictionary对象。 (其他对象是文本)

cumArray = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:
                                                         [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i", dayCounter] forKey:@"dayCounter"],[[dailyArray objectAtIndex:x]objectAtIndex:0],[[dailyArray objectAtIndex:x]objectAtIndex:1],[[dailyArray objectAtIndex:x]objectAtIndex:2], nil],nil];

我将数组保存在plist中,加载后一切看起来都很棒。

但是,当我对数组进行排序时,程序崩溃了。我尝试了以下各种组合:

        NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dayCounter" ascending:YES];
        [cumArray sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];

我是否需要字典项作为密钥?我可以更容易地对第一个对象进行排序吗?非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

有时使用太多嵌套表达式会掩盖实际发生的事情。例如,您创建的“简单”可变数组实际上包含一个嵌套的可变数组,而不是直接包含您尝试排序的字典。

所以不要这样:

cumArray = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:
                                                     [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i", dayCounter] forKey:@"dayCounter"],[[dailyArray objectAtIndex:x]objectAtIndex:0],[[dailyArray objectAtIndex:x]objectAtIndex:1],[[dailyArray objectAtIndex:x]objectAtIndex:2], nil],nil];

尝试这样做

NSDictionary *dict1 = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i", dayCounter]
                                                  forKey:@"dayCounter"]
NSArray *objs = [dailyArray objectAtIndex:x];
NSDictionary *dict2 = [objs objectAtIndex:0];
NSDictionary *dict3 = [objs objectAtIndex:1];
NSDictionary *dict4 = [objs objectAtIndex:2];

// Note: You might want to temporarily log the values of dict2 - 4 here to make sure they're
// really dictionaries, and that they all actually contain the key 'dayCounter'.

cumArray = [NSMutableArray arrayWithObjects:dict1, dict2, dict3, dict4, nil];

假设您确实拥有一个可变的字典数组,每个字典都包含键dayCounter,您在示例中显示的排序描述符应该可以正常工作。

答案 1 :(得分:-1)

您的设置毫无意义。你是在说自己只有数组中的第一个对象是包含键“@”dayCounter“(”其他对象是文本“)的字典。如果只有一个对象包含排序标准,它应该如何排序?

答案 2 :(得分:-1)

您需要使用方法对数组进行排序,例如 - (NSComparisunResult)compareDict 如果你必须比较2个字典并确定哪个应该在另一个上面排序(NSOrderedAscending),那么你需要“扩展”NSDictionary:

@interface NSDictionary (SortingAdditions) {}
- (NSComparisonResult)compareTo:(NSDictionary *)other;
@end
@implementation NSDictionary (SortingAddictions)
- (NSComparisonResult)compareTo:(NSDictionary *)other
{
  if( [self count] > [other count] )
  { return NSOrderedAscending; }
}
@end

此方法将根据NSDictionaries包含的对象数量对其进行排序。 您可以在此处返回的其他值包括:NSOrderedDescending和NSOrderedSame。

然后你可以用:

对可变数组进行排序
[SomeMutableArray sortUsingSelector:@selector(compareTo:)];

请记住,数组中的每个对象都需要是一个NSDictionary,否则你会得到一个异常:发送到实例blabla的无法识别的选择器

你可以为任何类型的对象做同样的事情,如果数组包含NSStrings,NSNumbers和NSDictionaries你应该采取不同的方法

相关问题