Custom class NSObject not key value coding compliant
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
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):
key
. setKey:
. (If the property is a Boolean
attribute, the getter accessor method has the form isKey
.) 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.
You need to declare every property that will be used:
@interface ContactObject : NSObject
@property (nonatomic,copy, readwrite) NSString* city;
@property (nonatomic, copy, readwrite) NSString* state;
+ (ContactObject *)testAdding;
@end
Or use a NSMutableDictionary object.
For example:
NSMutableDictionary* dict= [NSMutableDictionary new];
[dict setObject: @"Berlin" forKey: @"city"];
[dict setObject: @"Germany" forKey: @"state"];
You need to actually declare/implement properties. Key-Value Coding doesn't mean that every NSObject is automatically a key/value dictionary.
In this case you would need to declare:
@property (nonatomic, readwrite, copy) NSString* city;
@property (nonatomic, readwrite, copy) NSString* state;
in your @interface
declaration.
上一篇: 验证时返回收据数组
下一篇: 自定义类NSObject不符合键值编码