【问题标题】:How to use NSDate and NSString in a NSPredicate to fetch data from Core Data?如何在 NSPredicate 中使用 NSDate 和 NSString 从核心数据中获取数据?
【发布时间】:2015-03-13 18:21:59
【问题描述】:

当我在 iPhone 应用程序中从 Core 数据数据库中获取数据时遇到问题。

我正在使用此代码(第 1 行),它工作正常,这里我正在从日期获取数据:

注意:date的数据类型是NSDateselectedDate也是NSDate的类型。

第一行:

[NSPredicate predicateWithFormat:@"date == %@",selectedDate];

这段代码 (第 2 行) 在我获取系统数据时也可以正常工作:

第 2 行:

[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"systemName == '%@'",selectedSystemString]];

但是当我将上述两个谓词与这段代码结合起来时 (第 3 行)

第 3 行:

 [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(date == %@) AND (systemName == '%@')",selectedDate,selectedSystemString]];

应用程序在第 3 行崩溃,控制台中显示此错误消息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(date == 2015-01-15 18:30:00 +0000) AND (systemName == 'A')"'

*** First throw call stack:
(0x26494c1f 0x33c9cc8b 0x270feb55 0x270fc9bd 0x270fc93d 0x9b263 0x9c143 0xa8815 0x29a69f97 0x29b1bc0f 0x299cdc4d 0x29949aab 0x2645b3b5 0x26458a73 0x26458e7b 0x263a7211 0x263a7023 0x2d75a0a9 0x299b31d1 0xb1e7d 0x3421caaf)
libc++abi.dylib: terminating with uncaught exception of type NSException

【问题讨论】:

  • 使用(systemName == %@)
  • 感谢@flexaddicted 的评论。我已经使用了这段代码(systemName == %@)但仍然崩溃。 :(
  • 你收到同样的错误吗?
  • 是,*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法解析格式字符串”(日期 == 2015-01-15 18:30:00 +0000) AND (systemName == A)"'
  • 你在用这个吗? [NSPredicate predicateWithFormat:@"date == %@ AND systemName == %@",selectedDate,selectedSystemString];

标签: ios objective-c core-data nsdate nspredicate


【解决方案1】:

尝试使用复合谓词,

NSPredicate *datePredicate = [NSPredicate predicateWithFormat:@"date == %@",selectedDate];
NSPredicate *stringPredicate = [NSPredicate predicateWithFormat:@"systemName == %@",selectedSystemString];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[datePredicate, stringPredicate]];

使用andPredicateWithSubpredicates:方法的复合谓词类似于AND谓词,使用AND的解决方案是

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date == %@ AND systemName == %@",selectedDate, selectedSystemString];

【讨论】:

  • andPredicateWithSubpredicatesAND 完全一样。
  • 是的,我只是建议了不同的方法,根据@Stephen Darlington,真正的问题是 [NSString stringWithFormat: ] 将日期谓词转换为字符串。我用两种解决方案编辑了我的答案
  • 您能否编辑您的答案,解释这两种方法是相同的?我将删除我的反对票。谢谢。
【解决方案2】:

前两行之间的区别是第三行失败的原因。 (第二个也是不正确的,但因为您使用的是字符串而有效。)

如果您熟悉 SQL,这就像使用查询参数一样。

在第 1 行你说,这就是我正在寻找的这个参数(它恰好是一个日期)。

您在第 2 行中说,这就是我要查找的内容。没有参数。它应该是这样的:

[NSPredicate predicateWithFormat:@"systemName == %@",selectedSystemString];

第 3 行失败,因为您将日期转换为字符串(使用 NSDate 上的 description 方法);您的谓词没有参数。它应该看起来更像这样:

[NSPredicate predicateWithFormat:@"(date == %@) AND (systemName == %@)",selectedDate,selectedSystemString];

【讨论】:

  • 谢谢,现在我得到了这个问题的真正原因。非常感谢您提供这个问题的详细信息 :) _/_ (y)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 2020-02-22
相关资源
最近更新 更多