gpt4 book ai didi

objective-c - NSPredicate predicateWithFormat :(NSString*) inconsistency?

转载 作者:太空狗 更新时间:2023-10-30 03:35:24 28 4
gpt4 key购买 nike

在根据用户输入过滤我的 NSMutableDictionary 时,我创建了以下代码:

NSString *predicateString = [NSString stringWithFormat:@"SELF beginsWith[cd] %@", searchString];
NSPredicate *pred = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredKeys = [[myMutableDictionary allKeys] filteredArrayUsingPredicate:pred];

“searchString”被传递到具有此定义的方法中:

(NSString*) searchString

然而,这导致了以下异常:

...raised [ valueForUndefinedKey:]: this class is not key value coding-compliant for the key...

修复结果是:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF beginsWith[cd] %@", searchString];
NSArray *filteredKeys = [[myMutableDictionary allKeys] filteredArrayUsingPredicate:pred];

我不明白的是,为什么后者有效,而前者抛出异常。我在key value coding上读了一点,但我不明白它在这里如何应用。 (即仅通过更改 NSPredicate 的定义方式)有人可以启发我吗?

更新:作为对 jtbandes 评论的回应,我继续创建了一个 TestApp 项目来演示这个问题。 http://dl.dropbox.com/u/401317/TestApp1.tar.gz

最佳答案

答案是in the predicate programming guide .

String constants must be quoted within the expression—single and double quotes are both acceptable, ... If you use variable substitution using %@ ..., the quotation marks are added for you automatically. If you use string constants within your format string, you must quote them yourself

[我的重点]

predicateWithFormat 会为您加上引号,但 stringWithFormat 不会。如果您这样做,您的第一个示例可能会起作用:

NSString *predicateString = [NSString stringWithFormat:@"SELF beginsWith[cd] '%@'", searchString];
// ^ ^ single or double quotes

关于objective-c - NSPredicate predicateWithFormat :(NSString*) inconsistency?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6726467/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com