使用 KVC 查找 NSSet 中的最大值
我试图找到此 coredata 对象中 order 属性的最大值:
#import <Foundation/Foundation.h>
#import "Story.h"
@class Story;
@interface Sentence : NSManagedObject {
}
@property (nonatomic, retain) NSString *text;
@property (nonatomic, retain) NSString *image;
@property (nonatomic, retain) NSString *thumb;
@property (nonatomic, retain) NSNumber *order;
@property (nonatomic, retain) Story *belongsTo;
@end
Using KVC。我一直在使用 Apple 文档 作为资源(示例代码中似乎有错误 - 缺少 : 并且 @ 位于错误的位置,但也许我错过了一些东西?)
和我尝试使用的最新代码如下所示:
NSSet *sentences = [story sentences]; //this is a valid NSSet filled with 1 or n Sentence objects
NSNumber *maxOrder = [sentences valueForKeyPath:@"max.order"];
NSLog(@"maxOrder:", maxOrder);
我收到以下错误:
[33209:207] * 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<_PFCachedNumber 0xc4a9004>” valueForUndefinedKey:]:此类不符合键最大值的键值编码。'
如果答案很明显并且我没有抓住要点,我很抱歉,但我希望您能深入了解我做错了什么;关于这个主题的苹果文档似乎有点含糊。 谢谢!
I'm trying to find the maximum value in the order property in this coredata object:
#import <Foundation/Foundation.h>
#import "Story.h"
@class Story;
@interface Sentence : NSManagedObject {
}
@property (nonatomic, retain) NSString *text;
@property (nonatomic, retain) NSString *image;
@property (nonatomic, retain) NSString *thumb;
@property (nonatomic, retain) NSNumber *order;
@property (nonatomic, retain) Story *belongsTo;
@end
Using KVC. I've been using the Apple Documentation as a resource (which seems to have errors in the example code - missing : and having the @ in the wrong place, but perhaps I'm missing something?)
and the latest code I've tried to use looks like this:
NSSet *sentences = [story sentences]; //this is a valid NSSet filled with 1 or n Sentence objects
NSNumber *maxOrder = [sentences valueForKeyPath:@"max.order"];
NSLog(@"maxOrder:", maxOrder);
I get the following error:
[33209:207] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_PFCachedNumber 0xc4a9004> valueForUndefinedKey:]: this class is not key value coding-compliant for the key max.'
I'm sorry if the answer is obvious and I'm missing the point, but I'd appreciate some insight into what I'm doing wrong; the Apple Documentation on this topic seems a little vague.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您误读了文档。您的关键路径应该是
@"@max.order"
。注意字符串中的@。 @max 是集合运算符。不过,您是对的,该文档存在印刷错误。无论您在哪里看到
valueForKeyPath"@count"
或类似内容,您都应该在字符串前添加一个:@
,这会将其变成valueForKeyPath:@"@count “
。You've misread the documentation. Your key path should be
@"@max.order"
. Note the @ inside the string. @max is the collection operator.You are right that the documentation has typographical errors though. Wherever you see
valueForKeyPath"@count"
or the like, you should mentally add a:@
before the string, which turns it intovalueForKeyPath:@"@count"
.有趣的是,我从未意识到该文档中的示例是错误的。缺少分号和@。
你想要的语法是这样的:
Interesting, I never realized the examples in that doc were wrong. The semicolon and @ are missing.
The syntax you want is this: