2012-12-19 87 views
2

我有一個NSMutableArray Model對象。NSPredicate NSDate自定義對象篩選過濾器[NSDate date]

每個模型對象具有NSDate類型

我想使用NSPredicate過濾NSMutableArray的StartTime屬性。 我想要一個項目比現在老的數組,然後一個項目更新,然後現在。

這是我使用的代碼,但過濾的數組是空的。我會確保主數組中的項目有im過濾。

NSPredicate *pastPredicate = [NSPredicate predicateWithFormat:@"(startTime < %@)", [NSDate date]]; 
    NSPredicate *futurePredicate = [NSPredicate predicateWithFormat:@"(startTime >= %@)", [NSDate date]]; 

    self.pastReservations = [self.reservations filteredArrayUsingPredicate:pastPredicate]; 
    self.futureReservations = [self.reservations filteredArrayUsingPredicate:futurePredicate]; 

如果你知道我做錯了什麼,你們可以告訴我嗎?我不認爲我應該使用一個塊來使用內置類型的謂詞。

+0

該代碼似乎對我來說很好,在過濾數組並打印self.reservations中包含的對象之前添加一個斷點,我懷疑數組是空的。 –

+0

是的,我的所有日​​期都是零,因爲解析錯誤。 –

+0

@ adrian.coroian:如果您的問題已解決,您可以發佈自己的答案並將其標記爲已接受,以便其他人看到問題已解決。 –

回答

0

我的代碼是正確的。在那之前有代碼沒有正確工作,並且自我。像Ramy Al Zuhouri說的那樣,保留是空的。

0

爲什麼不這樣說:

NSDate* now = [NSDate date]; 

for(YourModelObject* obj in self.reservations) { 

    NSDate* objectDate = obj.date; 

    //if negative, "now" is earlier, so >= 0 is past 
    if([now timeIntervalSinceDate:objectDate] >= 0) { 
     [self.pastReservations addObject:obj]; 
    } else { 
     [self.futureReservations addObject:obj]; 
    } 

} 
+0

他的代碼沒有錯誤。 –

+0

看看我的方式是多好:) –