【问题标题】:Core Data: 'The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet.'核心数据:“ALL 或 ANY 运算符的左侧必须是 NSArray 或 NSSet。”
【发布时间】: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 的那一行设置断点。验证 patienttoday 值是否符合您的预期。 (请注意,您的代码示例当前未显示patient 是如何创建的。)如果其中一个值最终是包含单词“ALL”或“ANY”的字符串怎么办?并验证谓词的构造是否正确。根据 Apple 的谓词编程指南,如果 patient 是键路径而不是某种对象值,则需要在格式字符串中使用 %K 而不是 %@
  • 您能否显示处理 NSManagedObjectContextObjectsDidChangeNotification 的代码。还是这个?

标签: ios iphone core-data nspredicate


【解决方案1】:

如果问题是从不同线程访问核心数据,您可以确保使用正确的线程和 UIManagedObjectContext 的以下方法之一:

context.performBlockAndWait(block: () -> Void())
context.performBlock(block: () -> Void())

【讨论】:

    【解决方案2】:

    这个错误表明有两个线程试图访问数据库。我们不要忘记 CoreData 是非线程安全的。

    检查您的线程和对数据库的访问,因为线程中将存在访问数据库的竞争。

    希望这对您的问题有所帮助。如果您从不同的线程访问数据库,请尝试使用完成处理程序或 KVO 通知来管理线程对数据库的访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 2016-08-02
      • 2020-12-30
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多