排序/过滤NSFetchRequest如何写排序描述符将使用当前日期? [英] Sort/Filter NSFetchRequest how to write sort descriptor taht will use current date?

查看:158
本文介绍了排序/过滤NSFetchRequest如何写排序描述符将使用当前日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存储在 Core Data 2日期属性中,一个是过期日期,第二个是琥珀色日期(到期日期前X周的日期)。我想按以下方式对结果进行排序:




  • 琥珀色日期前的项目 - (绿色)现在<琥珀色

  • 琥珀色日期之后但到期日期之前的项目 - (琥珀色)琥珀色<=现在<到期

  • 项目过期或过期后 - (红色)过期<=现在



你可以帮我吗?

$ p $更多的研究,我发现我可以取得结果unsorted,把它在数组和排序数组和表将使用这个数组作为数据源 - 太多改变,让它在我的应用程序中工作。
也有可能使用额外的参数,将持有评估值基于上面的列表。然后,提取将需要2个步骤:


  1. 获取数据并对每个项目执行评估
  2. 获取这个解决方案是我最好的选择,所以任何人都可以帮我解决这个问题吗?

    编辑

    状态 c code $ @ $> c code $ @ $ @ $ @分配)int16_t状态;

    在表格I的 viewDidLoad 在获取排序结果之前调用休眠:

    pre $ NSFetchRequest fetchRequest = $ b $ {NSFetchRequest fetchRequestWithEntityName:@MyTable];
    NSSortDescriptor * sortTitle =
    [NSSortDescriptor sortDescriptorWithKey:@name
    ascending:YES];
    [fetchRequest setSortDescriptors:@ [sortByTitle]];

    NSFetchedResultsController * ctrl = [[NSFetchedResultsController alloc]
    initWithFetchRequest:fetchRequest
    managedObjectContext:[NSManagedObjectContext defaultContext]
    sectionNameKeyPath:nil
    cacheName:nil];

    NSError * fetchError = nil;
    if([ctrl performFetch:& fetchError] == NO){

    NSLog(@Error:perform fetch failed,%@,[fetchError description]);

    } else {
    //我们在这里有结果吗?
    id< NSFetchedResultsSectionInfo> sectionInfo =
    [ctrl.sections objectAtIndex:0];
    NSArray * items = [sectionInfo objects];
    for(int i = 0; i< item.count; i ++){
    CourseCD * item = items [i];
    NSLog(@%d - %@,i,item);
    [item evaluateState]; //类别添加这个方法


    code $ $ $ $ $ $ b

    这是类别中的方法

       - (State)evaluateState {
    CourseComplianceState pState = StateUnknown;
    if(self.expire == nil){
    [self setState:pState];
    返回pState;
    }

    NSDate * now = [[NSDate alloc] init];
    pState = StateNotExpired;
    $ b $ if([NSDate isDate:now inRangeFirstDate:self.thresholdDate
    lastDate:self.expireDate]){
    //琥珀
    pState = StateWithinThreshold;
    } else if([NSDate isDate:now inRangeFirstDate:self.expireDate
    lastDate:[NSDate distantFuture]]){
    // expired
    pState = StateExpired;
    }

    //
    [self setState:pState];

    NSLog(@ - evaluateState - );

    返回pState;



    $ b $这是状态结构

      enum {
    StateUnknown,
    StateNotExpired,
    StateWithinThreshold,
    StateExpired

    };
    typedef int16_t状态;

    然后在这个调用之后,我使用以下类型的目标调用,并使用控制器table。

      //稍后我将使用以下排序描述符
    NSSortDescriptor * sortState = [NSSortDescriptor
    sortDescriptorWithKey: @state
    升序:YES];
    NSSortDescriptor * sortExpire = [NSSortDescriptor
    sortDescriptorWithKey:@expire
    升序:YES];

    编辑

      NSSortDescriptor * sortByTitle = [NSSortDescriptor 
    sortDescriptorWithKey:@name
    升序:YES];
    NSFetchRequest * fetchRequest = [NSFetchRequest
    fetchRequestWithEntityName:@Course];
    [fetchRequest setSortDescriptors:@ [sortState,sortExpire,sortByTitle]];

    $ b $ self.resultsController = [[NSFetchedResultsController alloc]
    initWithFetchRequest:fetchRequest
    managedObjectContext:[NSManagedObjectContext defaultContext]
    sectionNameKeyPath:nil
    cacheName :零];

    self.resultsController.delegate = self;

    NSError * fetchError = nil;
    if([self.resultsController performFetch:& fetchError] == NO){

    NSLog(@Error:perform fetch failed,%@,[fetchError description]);






    但它只能按过期日期排序,状态被忽略或者没有通过第一次评估运行得到保存。



    编辑2014/06/10



    这是NSManagedObject类中的setter



    $ p $ // h
    @property(nonatomic,assign)int16_t州;

    //.m
    @synthesize state = _state;
    - (void)setState:(int16_t)state {
    _state = state;

    NSError * error = nil;
    [[NSManagedObjectContext defaultContext] save:& error];
    if(error!= nil){
    NSLog(@setState中的错误,细节:%@,[error description]);




    $ b $最终编辑 - 已解决
    $ b

    解决方法是:
    删除 @synthesise state = _state; - (void)setState:(int16_t)state {} 并离开 @dynamic state 。然后在 evaluateState 代替 [self setState:pState]; 我用了 self.state = pState; 现在按需要排序。现在的问题是为什么合成的属性,它没有工作?解决方案

解决方案

解决方案是:删除合成状态= _状态; - (void)setState:(int16_t)state {} 并保持@dynamic状态。然后在 evaluateState 代替 [self setState:pState]; 我用了 self.state = pState; 现在按需要排序。


I'm storing in Core Data 2 date properties, one is expire date and second is "amber" date (the date that is X weeks before expire date). I want to sort results in following way:

  • items before the amber date - (green) now < amber
  • items after amber date but before expire date - (amber) amber <= now < expire
  • items on or after expire date - (red) expire <= now

Can you help me with that?

UPDATE After more research I've found that I could fetch results unsorted, put it in the array and sort the array and table would use this array as data source - too much to change to have it working in my app. Also there is possibility to use extra parameter which will hold evaluated value based on the list above. The fetch then would require 2 steps:

  1. fetch data and run evaluation on each item
  2. fetch sorted data by this evaluated property

The latter solution is my best option, so could anyone help me with that part?

EDIT

The state property is defined as int16_t

@property (nonatomic, assign) int16_t state;

In viewDidLoad of the view with table I call fallowing before fetching the sorted results:

 NSFetchRequest *fetchRequest = 
[NSFetchRequest fetchRequestWithEntityName:@"MyTable"];
    NSSortDescriptor *sortTitle = 
    [NSSortDescriptor sortDescriptorWithKey:@"name"
                                  ascending:YES];
    [fetchRequest setSortDescriptors:@[sortByTitle]];

    NSFetchedResultsController *ctrl = [[NSFetchedResultsController alloc]
                initWithFetchRequest:fetchRequest
                managedObjectContext:[NSManagedObjectContext defaultContext]
                  sectionNameKeyPath:nil
                           cacheName:nil];

    NSError* fetchError = nil;
    if([ctrl performFetch:&fetchError] == NO) {

        NSLog(@"Error: perform fetch failed, %@",[fetchError description]);

    } else {
        //do we have results here?
        id <NSFetchedResultsSectionInfo> sectionInfo = 
                                      [ctrl.sections objectAtIndex:0];
        NSArray * items = [sectionInfo objects];
        for (int i=0; i<items.count; i++) {
            CourseCD* item = items[i];
            NSLog(@"%d - %@",i,item);
            [item evaluateState];//category adds this method
        }
    }

This is the method from category

-(State) evaluateState {
    CourseComplianceState pState = StateUnknown;
    if (self.expire == nil) {
        [self setState:pState];
        return pState;
    }

    NSDate* now = [[NSDate alloc] init];
    pState = StateNotExpired;

    if ([NSDate isDate:now inRangeFirstDate:self.thresholdDate 
              lastDate:self.expireDate]) {
        //amber
        pState = StateWithinThreshold;
    } else if ([NSDate isDate:now inRangeFirstDate:self.expireDate 
                     lastDate:[NSDate distantFuture]]){
        //expired
        pState = StateExpired;
    }

    //
    [self setState:pState];

    NSLog(@" - evaluateState -");

    return pState;
}

And this is the State struct

enum {
    StateUnknown,
    StateNotExpired,
    StateWithinThreshold,
    StateExpired

};
typedef int16_t State;

Then after this call I use the destination call with following sorts and I'm using controller that works with table.

//later I use following sort descriptors
NSSortDescriptor *sortState = [NSSortDescriptor 
                                  sortDescriptorWithKey:@"state"
                                              ascending:YES];
NSSortDescriptor *sortExpire = [NSSortDescriptor 
                                  sortDescriptorWithKey:@"expire"
                                              ascending:YES];

EDIT

NSSortDescriptor *sortByTitle = [NSSortDescriptor 
                                   sortDescriptorWithKey:@"name" 
                                               ascending:YES];
NSFetchRequest *fetchRequest = [NSFetchRequest 
                                 fetchRequestWithEntityName:@"Course"];
[fetchRequest setSortDescriptors:@[sortState,sortExpire,sortByTitle]];


self.resultsController = [[NSFetchedResultsController alloc] 
                           initWithFetchRequest:fetchRequest
                   managedObjectContext:[NSManagedObjectContext defaultContext]
                             sectionNameKeyPath:nil
                                      cacheName:nil];

self.resultsController.delegate = self;

NSError* fetchError = nil;
if([self.resultsController performFetch:&fetchError] == NO) {

    NSLog(@"Error: perform fetch failed, %@",[fetchError description]);

}

But it only sorts by the expire date and state is ignored or not saved by this first evaluation run.

EDIT 2014/06/10

This is the setter in the NSManagedObject class

//.h
@property (nonatomic, assign) int16_t state;

//.m
@synthesize state=_state;
-(void) setState:(int16_t)state {
    _state = state;

    NSError* error = nil;
    [[NSManagedObjectContext defaultContext] save:&error];
    if(error != nil){
        NSLog(@"Error in setState, details:%@",[error description]);
    }
}

FINAL EDIT - RESOLVED

The resolution was to: remove @synthesise state = _state; and -(void) setState:(int16_t)state {} and leave @dynamic state. Then in evaluateState instead of [self setState:pState]; I used self.state=pState; and now it sorts as required. The question now is why with synthesised property it didnt worked?

解决方案

The resolution was to: remove @synthesise state = _state; and -(void) setState:(int16_t)state {} and leave @dynamic state. Then in evaluateState instead of [self setState:pState]; I used self.state=pState; and now it sorts as required.

这篇关于排序/过滤NSFetchRequest如何写排序描述符将使用当前日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆