0

I am using setValuesForKeysWithDictionary to populate my model object . Model object is defined as

@interface Media : NSObject
{
    NSString *userId;
    NSString *mediaType;
}

@property(nonatomic,copy) NSString *userId;
@property(nonatomic,copy) NSString *mediaType;

property synthesization looks like ,

@implementation Media
@synthesize userId;
@synthesize mediaType;

and I initialize the class as follows,

NSMutableDictionary *dic = [NSMutableDictionary new];
[dic setValue:@"aaa" forKey:@"userId"];
[dic setValue:@"bbb" forKey:@"mediaType"];

Media *obj = [[Media alloc] init];
[obj setValuesForKeysWithDictionary:dic];

This crashes with the message

'[<Media 0x8a9f280> valueForUndefinedKey:]: this class is not key value coding-compliant    for the key aaa.'

How come setValuesForKeysWithDictionary: treat my value as the key ?? or have I misunderstood the purpose of the setValuesForKeysWithDictionary: function ?

rustylepord
  • 5,681
  • 6
  • 36
  • 49
  • Where are you putting this code? I copied the code below "and I initialize the class as follows" into my app delegate, and defined a new class Media with the .h file you show. It worked fine for me. – rdelmar Aug 17 '12 at 21:42
  • My initial thought is that it has something to do with how/if you are synthesizing your properties in the implementation of Media. I can't reproduce your issue with the latest version of Xcode (4.4.1) though because synthesizing is done automatically. – jordanperry Aug 18 '12 at 00:09
  • Actually for testing purposes I am trying out this in appDelegate, I am splitting hairs all night because of this issue. So weird. – rustylepord Aug 18 '12 at 05:32
  • I am using xCode 4.3.3. and what's funny is If I modified it to [dic setValue:@"userId" forKey:@"userId"]; [dic setValue:@"mediaType" forKey:@"mediaType"]; , It runs without a problem. – rustylepord Aug 18 '12 at 05:54

2 Answers2

0

Finally found the answer. It wasn't about setting the values rather the retrieval part. I was using the following method to read back the values from the model.

-(NSDictionary*) dictionaryRepresentation
{ 
   return [self dictionaryWithValuesForKeys:[NSArray arrayWithObjects:,userId,mediaType,     nil]];
}

As you can see I have used plain variable names instead of keys. @"userId", @"mediaType".

I changed xcode to a different font theme recently and still getting used to the new set of font colors. Thanks guys for your valuable time.

rustylepord
  • 5,681
  • 6
  • 36
  • 49
0

Add @objc as prefix while declaring the variable like this.

class Customer: NSObject
{
    @objc var name: String?
    @objc var email: String?
}

It should work.

mfaani
  • 33,269
  • 19
  • 164
  • 293
Amit Thakur
  • 1,081
  • 12
  • 14