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 n开发者_如何学编程ot 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!
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 into valueForKeyPath:@"@count"
.
Interesting, I never realized the examples in that doc were wrong. The semicolon and @ are missing.
The syntax you want is this:
NSNumber *maxOrder = [sentences valueForKeyPath:@"@max.order"];
精彩评论