2010-10-28 58 views
0

我試圖找到這個coredata對象的順序屬性的最大值找到最大值:使用KVC在NSSet中

#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 

使用KVC。我一直在使用Apple Documentation作爲資源(在示例代碼中似乎有錯誤 - 錯過了:在錯誤的地方有@,但也許我錯過了什麼?)

和最新的代碼I已經試過用看起來是這樣的:

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] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_PFCachedNumber 0xc4a9004> valueForUndefinedKey:]: this class is not key value coding-compliant for the key max.'

對不起,如果答案是顯而易見的,我錯過了點,但我瞭解我做錯了什麼;關於這個話題的Apple文檔似乎有些模糊。 謝謝!

回答

2

您誤解了文檔。您的關鍵路徑應該是@"@max.order"。請注意字符串中的@。 @max是收集操作員。

你說得對,儘管文檔有印刷錯誤。無論你在哪裏看到valueForKeyPath"@count"之類的東西,你都應該在字符串前加上一個:@,然後把它變成valueForKeyPath:@"@count"

1

有趣的是,我從來沒有意識到該文檔中的例子是錯誤的。分號和@缺失。

你想要的語法是這樣的:

NSNumber *maxOrder = [sentences valueForKeyPath:@"@max.order"];