代码之家  ›  专栏  ›  技术社区  ›  RunLoop

用于比较核心数据日期属性的月份组件的谓词

  •  1
  • RunLoop  · 技术社区  · 15 年前

    我有一个具有日期属性的核心数据实体。我想写一个谓词来提取特定月份内的所有日期,例如七月,而不考虑年份。如何实现这一目标?谢谢

    2 回复  |  直到 11 年前
        1
  •  6
  •   Dave DeLong    15 年前

    您可以在您的实体上创建一个新方法,我们将调用它 monthOfDate . 此方法只使用 [self dateAttribute] NSDateComponents 提取日期的月份。

    然后您可以编写一个谓词:

    //assuming 1-based month indexing
    NSPredicate * julyEntities = [NSPredicate predicateWithFormat:@"monthOfDate = 7"]; 
    

    这里的技巧是认识到谓词的左键路径将导致方法调用。因此,如果将左键路径设置为“monthofdate”,它最终将调用 月历 方法,并使用方法的返回值作为谓词中的比较值。整洁!

        2
  •  0
  •   BossBols    11 年前

    还不能评论,所以请这样问。

    你是怎么做到的?我试图在托管对象类中添加一个方法,但一旦谓词激发,它就说它找不到keypath monthofdate?

    用两个文件更新:

    h文件:

    @property (nonatomic,retain) NSNumber *monthOfDate;
    -(NSNumber *)monthOfDate;
    

    m文件:

    @synthesize monthOfDate;
    
    -(NSNumber *) monthOfDate
    {
    NSDate *date = [self start];
    NSDateComponents *components = [[NSCalendar currentCalendar]components: NSCalendarUnitMonth fromDate:date];
    NSNumber *month = [NSNumber numberWithInteger:[components month]];
    return month;
    }
    

    更新2

    上面的代码位于自动生成的事件类(nsmanaged对象)中。稍后我可能会将我的自定义代码移到一个类别中,但到目前为止,不需要修改模型。

    下面是带有上述谓词的FetchedResultsController(在uiviewController类中)设置:

    nsfetchRequest*fetchRequest=[[nsfetchRequest alloc]init];

    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Event" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSSortDescriptor *sortfix = [[NSSortDescriptor alloc]initWithKey:@"timeStamp" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortfix,nil]];
    [fetchRequest setFetchBatchSize:20];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"client == %@ AND monthOfDate = %d", clientMO,[NSNumber numberWithInteger:6]];
    [fetchRequest setPredicate:predicate];
    
    
    NSFetchedResultsController *theFetchedResultsController =
    
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:managedObjectContext sectionNameKeyPath:sectionKeyPathProperty
                                                   cacheName:nil];
    
    //sectionKeyPathProperty is a variable that let's me choose one of multiple transient properties I have created for creating relevant sections.
    
    self.fetchedResultsControllerClient = theFetchedResultsController;
    _fetchedResultsControllerClient.delegate = self;
    
    return _fetchedResultsControllerClient;