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

cre*_*eps 5 crash compare core-data 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;

}
Run Code Online (Sandbox Code Playgroud)

这条线

fetchedObjs = [[[self managedObjectContext] executeFetchRequest:fetch error:&fetchError] retain]; 
Run Code Online (Sandbox Code Playgroud)

崩溃时出错:

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

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

Dav*_*ong 10

你的问题是这样的:

[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"originTime >= %@", sevenDaysAgo]];
Run Code Online (Sandbox Code Playgroud)

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

[NSPredicate predicateWithFormat:@"originTime >= %@", sevenDaysAgo];
Run Code Online (Sandbox Code Playgroud)

这将工作得很好.