Custom class NSObject not key value coding compliant

matttrakker picture matttrakker · Jan 5, 2013 · Viewed 7.8k times · Source

Possible Duplicate:
Why is my object not key value coding-compliant?

I'm having a dictionary and I want to add keys/values to a custom class, but i always get the error, that the class is not KVC compliant, but the Apple documents state that it should be.

My code:

ContactObject.h:

@interface ContactObject : NSObject
     + (ContactObject *)testAdding;
@end

ContactObject.m:

@implementation ContactObject

- (id)init {
    self = [super init];
    if (self) {
        // customize

    }

    return self;

}

+ (ContactObject *)testAdding
{
    // create object
    ContactObject *theReturnObject = [[ContactObject alloc] init];

    [theReturnObject setValue:@"Berlin" forKey:@"city"];
    [theReturnObject setValue:@"Germany" forKey:@"state"];

    return theReturnObject;

}

@end

I think I'm missing something very stupid :)

Please, any help appreciated ...

Greetings, matthias

Answer

Jack picture Jack · Jan 5, 2013

Actually to be KVC compliant:

How you make a property KVC compliant depends on whether that property is an attribute, a to-one relationship, or a to-many relationship. For attributes and to-one relationships, a class must implement at least one of the following in the given order of preference (key refers to the property key):

  1. The class has a declared property with the name key.
  2. It implements accessor methods named key and, if the property is mutable, setKey:. (If the property is a Boolean attribute, the getter accessor method has the form isKey.)
  3. It declares an instance variable of the form key or _key.

I don't see any of these three implemented. You need to have at least properties that you are trying to set through KVC, the default NSObject implementation is able to set properties through setValue:forKey: but you must declare them.