views:

588

answers:

1

I'm trying a basic test of sorting an NSManagedObject subclass. I set up a basic subclass "TestClass" with two attributes: stringField and numberField. They use the standard Obj-C 2.0 accessor protocol:

@interface TestClass : NSManagedObject
@property (retain) NSString *stringField;
@property (retain) NSNumber *numberField;
@end

@implementation TestClass
@dynamic stringField;
@dynamic numberField;
@end

When I try to fetch instances of this entity, I can fetch based on either attribute. However, if I use a sort descriptor, the numberField is said to not be KVC-compliant.

Within the model, I set the numberField to Int64, but I'm confused. I thought the wrapper (NSNumber) would handle the KVC problem. What do I need to do to make this work?

+2  A: 

Some initial "Is the computer on?"-type questions:

  1. Does your model specify that the managed object class for your entity is TestClass?
  2. Are you sure you spelled numberField correctly when specifying the key in your sort descriptor?
  3. Is numberField a transient attribute in your model?

These are the common issues that I can think of that might cause such an error when fetching with a sort descriptor, the first one especially.

Also, this won't affect KVC, but your attributes' property declarations should be (copy) rather than (retain) since they're "value" classes that conform to the NSCopying protocol and may have mutable subclasses. You don't want to pass a mutable string in and mutate it underneath Core Data. (Yeah, there's no NSMutableNumber or NSMutableDate in Cocoa, but that doesn't prevent creating MyMutableNumber or MyMutableDate subclasses...)

Chris Hanson
Yes, it does specify that the MO class is TestClass. No, not transient. The error was #2. Bad spelling (numberKey instead of numberfield). How stupid. Thanks!Also took note about copy. Thanks.
Daniel Child
If the error was #2, you should accept the answer. :)
Chris Hanson
(copy) is the right attribute, except in NSManagedObject subclasses where "The property accessor methods Core Data generates are by default (nonatomic, retain)—this is the recommended configuration." and " You should use copy sparingly as it increases overhead." [Source: Apple's Core Data Programming Guide >> Managed Object Accessor Methods]
Elise van Looij