开发者

NSManagedObject subclasses and setValuesForKeysWithDictionary:

I am initializing a NSManagedObject subclass using:

- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues

I am also knowingly giving it the undefined keys, which of course should throw an exception.

So, I have implemented:

- (void)setValue:(id)value forUndefinedKey:(NSString *)key

If a key is undefined, I map it to the correct key.

However, my implementation never gets called, instead NSManagedObject's implementation is used, which in turn still throws an exception.

Is there a behavior (or bug) that prevents setValuesForKeysWithDictionary: from using any NSManagedObject subclass implementation of setValue:forUndefinedKey:?

Adding code as requested, but since I am just implementing an existing method, which doesn't get called, I don't know how much help it will be:

In the context:

- (Company*)companyWithDictionary:(NSDictionary*)values{

    Company* newCompany = (Company*)[NSEntityDescription insertNewObjectForEntityForName:@"Company" inManagedObjectContext:self];

    [newCompany setValuesForKeysWithDictionary:values];

    return newCompany;
}

In the Company subclass (never called):

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{

    if([key isEqualToString:idKey]){

        [self setValue:value forKey:@"uniqueID"];

    }else if([key isEqualToString:descriptionKey]){

        [self setValue:value forKey:@"descriptionText"];

    }else if([key isEqualToString:timeUpda开发者_如何学CtedKey]){

        [self setValue:value forKey:@"dateUpdated"];

    }else{

        [super setValue:value forUndefinedKey:key];

    } 
}


There's definitely nothing intrinsic to NSManagedObject that prevents this; I'm doing exactly this in the app I'm working on. Can you post more of your code?

One thought, also: are you sure it's setValue:forUndefinedKey: that's throwing the exception? For a managed object, I'm pretty sure you also need to implement valueForUndefinedKey: (the getter) to make things work properly.


Simple question, but are you specifying your NSManagedObject subclass's class name for the entity in your model?

Also, you said you're initializing the managed object ... how? You should be inserting it via +[NSEntityDescription insertNewObjectForEntityForName: inManagedObjectContext:] in most cases, unless you have a good reason not to.


A quick class-dump of the CoreData framework indicates that NSManagedObject also overrides setValuesForKeysWithDictionary:, so it looks like it definitely is doing some customization for that method, perhaps for performance reasons or something like that. I would probably just write my own method equivalent to setValuesForKeysWithDictionary: and call that instead to avoid the whole mess. Something like this:

- (void)mySetValuesForKeysWithDictionary:(NSDictionary*)dict
{
    for (NSString* key in dict)
        [self setValue:[dict objectForKey:key] forKey:key];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜