dynamically set the key for Key

I have a class called mycallback:

[mycallback setValue:[code objectForKey:@"abc"] forKey:@"abc"];

It gets called for a lot of my controllers. THe thing is i pull data from a mysql database and I send it to mycallback. So I may not know what the key is. And in addition to that, I don't want to declare instance variables inside mycallback class because I want it separated.

Unfortunately, if the code as is runs above, I get this message:

exception 'NSUnknownKeyException', reason: '[<CallbackClass 0x7b6c5d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key fence.'

So I want to dynamically set the keys but not inside mycallback. So I create a category for NSDictionary and add valueForUndefinedKey method:

- (id)valueForUndefinedKey:(NSString *)key
{
    NSLog(@"This key not being called %@", key);
    return nil;
}

but 1) valueForUndefinedKey is not called and 2) I'm not sure what to put in there to make that error go away.

thanks for response.


You've defined valueForUndefinedKey: which is what deals with returning values. But in your code snippet it looks like you are trying to set a value for an undefined key. In which case, the method to use is:

setValue:forUndefinedKey:

An example, based on what it looks like you are trying to do:

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"Attempting to set value: %@ for key: %@", value, key);
}
链接地址: http://www.djcxy.com/p/19234.html

上一篇: 如何检查是否从网络安装了应用程序

下一篇: 动态设置Key的密钥