iOS NSDate核心数据比较获取请求无效

时间:2011-03-07 21:22:48

标签: core-data crash compare nsdate nspredicate

也许你可以帮助我。这段代码出了什么问题:

-(NSMutableArray *)returnItemsWithName:(NSString *)name{

    NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
    NSEntityDescription *entity=[NSEntityDescription entityForName:@"XYZ" inManagedObjectContext:[self managedObjectContext]];
    [fetch setEntity:entity];
    NSDate *sevenDaysAgo = [appDelegate dateByAddingDays:-7 toDate:[NSDate date]];
NSPredicate *pred= [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"originTime >= %@", sevenDaysAgo]];
    [fetch setPredicate:pred];
    NSError *fetchError=nil;
    NSMutableArray *fetchedObjs = [[[self managedObjectContext] executeFetchRequest:fetch error:&fetchError] retain];
    if (fetchError!=nil) {
        return nil;
    }

    return fetchedObjs;

}

fetchedObjs = [[[self managedObjectContext] executeFetchRequest:fetch error:&fetchError] retain]; 

因错误而崩溃:

* 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串“originTime&gt; = 2011-02-28 21:07:37 +0000”'< / p>

所有对象都不是nil,而且originDate也是CD数据库中的NSDate

1 个答案:

答案 0 :(得分:10)

你的问题是:

[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"originTime >= %@", sevenDaysAgo]];

predicateWithFormat: 已经想要一个格式字符串。这是不必要的,正如你所发现的那样,做你正在做的事是错误的。虽然这很容易解决:

[NSPredicate predicateWithFormat:@"originTime >= %@", sevenDaysAgo];

这样就可以了。