1

我想按日期对可变数组进行排序。我的数组包含几个带有键的字典:key1,key2,birthday。现在,我必须按它的生日键排序:我知道这可以使用:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"birthday" ascending:YES]; 
[myArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

但我的问题是我只想对那些不包含空生日字段的数组进行排序。我的数组将包含几个空的生日字段。我不想对这些进行排序。最后我必须通过[self.mTable reloadData];.

4

2 回答 2

2

首先收集所有没有生日的对象的索引。

NSIndexSet *indexSet = [NSIndexSet indexSet];
[array enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
    if(![[dict allKeys] containsObject:@"birthday"]){
        [indexSet addIndex:idx];
    }
}];

现在将它们从原始数组中删除

[array removeObjectsAtIndexes:indexSet];

使用比较器块,排序看起来像

[array sortUsingComparator: ^(NSDictionary *d1, NSDictionary *d2) {    
    NSDate *date1 = [d1 objectForKey:@"birthday"];
    NSDate *date2 = [d2 objectForKey:@"birthday"];

    return [date1 compare:date2]
}
于 2012-06-14T07:29:24.713 回答
0

创建一个不同的数组来支持您的表格视图,如下所示:

NSDictionary* obj1 = [NSDictionary dictionaryWithObject: [NSDate date] forKey: @"birthday"];
NSDictionary* obj2 = [NSDictionary dictionaryWithObject: [NSDate dateWithTimeIntervalSince1970: 0] forKey: @"birthday"];
NSDictionary* obj3 = [NSDictionary dictionaryWithObject: @"wow" forKey: @"no_birthday"];

NSArray* all = [NSArray arrayWithObjects: obj1, obj2, obj3, nil];
NSArray* onlyWithBirthday = [all valueForKeyPath: @"@unionOfObjects.birthday"];

如果您需要表格视图的完整对象,请继续执行以下代码:

NSPredicate* filter = [NSPredicate predicateWithFormat: @"SELF.birthday IN %@", onlyWithBirthday];
NSArray* datasource = [all filteredArrayUsingPredicate: filter];

然后,您可以应用您选择的排序方法。

于 2012-06-14T08:52:08.107 回答