当我从iPhone应用程序的Core数据数据库中获取数据时,我遇到了一个问题。
我正在使用此代码(第1行),它工作正常,这里我从日期中获取数据:
注意:的date
数据类型为NSDate
,selectedDate
也是NSDate
的类型。
第1行:
[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
最佳答案
您前两行的区别是第三行失败的原因。 (第二个也不正确,但是可以使用,因为您使用的是字符串。)
如果您熟悉SQL,就好比使用查询参数。
在第1行中,您说的是这就是我要使用的此参数(恰好是日期)所要查找的内容。
在第2行中,您说的是我要找的东西。没有参数。应该是这样的:
[NSPredicate predicateWithFormat:@"systemName == %@",selectedSystemString];
第3行失败,因为您将日期转换为字符串(使用
description
上的NSDate
方法);您的谓词没有参数。它看起来应该像这样:[NSPredicate predicateWithFormat:@"(date == %@) AND (systemName == %@)",selectedDate,selectedSystemString];
关于ios - 如何在NSPredicate中使用NSDate和NSString从Core Data中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27962061/