2016-07-27 73 views
1

我需要創建一個謂詞,它需要使用屬性creationDate(它是一個NSDate對象)過濾對象列表。我想獲取具有相同日期和月份但不是同一年的對象列表。實際上,我想要過去發生在今天(如日/月)的物體。我如何創建這個謂詞?例如:今天是2016年7月27日,我希望將7月27日的所有對象設置爲creationDate。NSPredicate NSDate按日/月但不是年份過濾

回答

3

首先,提取日期和月份從日......

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date]; 
NSInteger day = [components day]; 
NSInteger month = [components month]; 

接下來,(單程)建立一個謂語...

[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) { 
    // object must be cast to the type of object in the list 
    MyObject *myObject = (MyObject *)object; 
    NSDate *creationDate = myObject.creationDate; 

    // do whatever you want here, but this block must return a BOOL 
}]; 

把這些想法在一起。 ...

- (NSPredicate *)predicateMatchingYearAndMonthInDate:(NSDate *)date { 
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date]; 
    NSInteger day = [components day]; 
    NSInteger month = [components month]; 

    return [NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) { 
     MyObject *myObject = (MyObject *)object; 
     NSDate *creationDate = myObject.creationDate; 
     NSDateComponents *creationComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:creationDate]; 
     NSInteger creationDay = [creationComponents day]; 
     NSInteger creationMonth = [creationComponents month]; 
     return day == creationDay && month == creationMonth; 
    }]; 
} 

就是這樣。使用一些NSDate構建謂詞,這些人是你想要在數組中匹配的日期和月份,然後在數組上運行該謂詞(filteredArrayUsingPredicate:)。

NSDate *today = [NSDate date]; 
NSPredicate *predicate = [self predicateMatchingYearAndMonthInDate:today]; 
NSArray *objectsCreatedToday = [myArray filteredArrayUsingPredicate:predicate]; 
+0

您使用predicateWithBlock創建了NSPredicate,但有時不支持(例如在Photos框架中)。我怎樣才能獲得相同的結果,避免使用該塊? –

相關問題