使用 NSPredicate 的 `array[FIRST]` 运算符
Using NSPredicate's `array[FIRST]` operator
我在 Apple 的 documentation 中看到有一个 array[FIRST]
运算符,这正是我编写所需谓词所需要的。不幸的是,文档没有提供任何示例,而且我不知道如何将其清楚地放入谓词中。
所以,举例来说,我会有类似 [NSPredicate predicateWithFormat:@"array[FIRST] IN %@", @[@1, @2, @3]
的东西。这当然会引发异常:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFConstantString 0x100001058> valueForUndefinedKey:]: this class is not key value coding-compliant for the key array.'
因为这个谓词最终会进入核心数据模型文件,我需要用字符串格式表示它,所以任何涉及代码的解决方案都不会起作用。
在格式字符串中替换 %@
值并将 SELF
替换为被评估的对象后,谓词需要有意义。你的谓词说:"is the first object in an unknown symbol called 'array' contained within the literal array 1,2,3?"
考虑以下示例...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF[FIRST] == %@", @1];
BOOL result = [predicate evaluateWithObject:@[@1, @2, @3]];
// result will be YES
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF[FIRST] == %@", @2];
BOOL result = [predicate evaluateWithObject:@[@1, @2, @3]];
// result will be NO
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@[FIRST] == SELF", @[@1, @2, @3]];
BOOL result = [predicate evaluateWithObject:@1];
// result will be YES
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@[FIRST] == SELF", @[@1, @2, @3]];
BOOL result = [predicate evaluateWithObject:@2];
// result will be NO
我在 Apple 的 documentation 中看到有一个 array[FIRST]
运算符,这正是我编写所需谓词所需要的。不幸的是,文档没有提供任何示例,而且我不知道如何将其清楚地放入谓词中。
所以,举例来说,我会有类似 [NSPredicate predicateWithFormat:@"array[FIRST] IN %@", @[@1, @2, @3]
的东西。这当然会引发异常:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFConstantString 0x100001058> valueForUndefinedKey:]: this class is not key value coding-compliant for the key array.'
因为这个谓词最终会进入核心数据模型文件,我需要用字符串格式表示它,所以任何涉及代码的解决方案都不会起作用。
在格式字符串中替换 %@
值并将 SELF
替换为被评估的对象后,谓词需要有意义。你的谓词说:"is the first object in an unknown symbol called 'array' contained within the literal array 1,2,3?"
考虑以下示例...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF[FIRST] == %@", @1];
BOOL result = [predicate evaluateWithObject:@[@1, @2, @3]];
// result will be YES
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF[FIRST] == %@", @2];
BOOL result = [predicate evaluateWithObject:@[@1, @2, @3]];
// result will be NO
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@[FIRST] == SELF", @[@1, @2, @3]];
BOOL result = [predicate evaluateWithObject:@1];
// result will be YES
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@[FIRST] == SELF", @[@1, @2, @3]];
BOOL result = [predicate evaluateWithObject:@2];
// result will be NO