【发布时间】:2014-03-31 18:03:49
【问题描述】:
如果今天的对象已经存在,我有一个查询 Core Data 的方法。
我的代码:
CoreDataHelper *cdh = [(MRMedSafeAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
NSManagedObjectContext *context = [cdh context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"BMI" inManagedObjectContext:context];
[request setEntity:entity];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:day];
[comps setMonth:month];
[comps setYear:year];
NSDate *today = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSLog(@"patient: %@", patient);
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(patient == %@) AND (erstellt_am == %@)", patient, today];
[request setPredicate:pred];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
数据模型:
bmi.patient 与 Patient 是一对一关系。
我不明白出了什么问题,我的谓词中甚至没有 ALL 或 ANY 子句。
谁能启发我?
【问题讨论】:
-
错误是关于哪一行代码?我假设它是
NSPredicate *pred,但请告诉我们 Xcode 告诉您的内容。 -
在 NSLog 行之后失败并显示以下消息:
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet. with userInfo (null) 2014-02-28 00:55:06.652 MedSafeStatic[830:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet.' -
更令人惊讶的是,它并不总是失败,似乎在第二次运行该方法后它会失败......???
-
在创建 NSPredicate 的那一行设置断点。验证
patient和today值是否符合您的预期。 (请注意,您的代码示例当前未显示patient是如何创建的。)如果其中一个值最终是包含单词“ALL”或“ANY”的字符串怎么办?并验证谓词的构造是否正确。根据 Apple 的谓词编程指南,如果patient是键路径而不是某种对象值,则需要在格式字符串中使用%K而不是%@。 -
您能否显示处理 NSManagedObjectContextObjectsDidChangeNotification 的代码。还是这个?
标签: ios iphone core-data nspredicate