2012-06-14 117 views
1

我想按日期排序可變數組。我的數組包含幾個鍵的dict說:KEY1,KEY2,birthday.Now,我有它的生日鍵排序: 我知道,這是可以做到用:按日期排序NSMutableArray

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

但我的問題是,我想僅排序那些不包含空白生日字段的數組。我的數組將包含幾個空的生日字段。我不想對這些進行排序。 最後,我必須通過[self.mTable reloadData];加載這些表格視圖。

+0

定義「我不想對這些進行排序」。你想要他們在列表的最後?或者在他們之前的地方? – coverback

+0

他們將在數組中,但在表視圖中,他們不應該存在。 – iCoder4777

回答

2

首先收集沒有生日的所有物體的指數。

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

現在從原來的陣列

[array removeObjectsAtIndexes:indexSet]; 

使用comparator block刪除,排序可能看起來像

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

    return [date1 compare:date2] 
} 
+0

但是這也會列出那些生日場是零的。我不想顯示這些字段 – iCoder4777

+0

以便在排序排序之前或之後進行篩選。 – vikingosegundo

+0

請參閱我的編輯 – vikingosegundo

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

那麼你可以申請您選擇的排序方法。