Search code examples
objective-ctypedefkey-value-coding

#typedef and KVC in ObjC


I have a class that looks like this:

@interface Properties : NSObject {
@private
    NSNumber* prop1;
    NSNumberBool* prop2;
    //etc

where NSNumberBool is a typedef:

// in MyApp_Prefix.pch
typedef NSNumber NSNumberBool;

I have all the required @property and @synthesize declarations to make prop1 and prop2 properties.

Everything compiled and worked fine until I tried to access prop2 by [myProperties valueForKey:@"prop2"]. This gives me a "class is not key-value compliant" error. However, many similar calls work fine:

myProperties.prop2; //works
[myProperties prop2]; //works
[myProperties valueForKey:@"prop1"]; //works
[myProperties valueForKey:@"prop2"] // throws NSUnknownKeyException ??

What is going on here, and how can I fix it?

Thanks,


Solution

  • This is pretty an old post, but I came to it while looking for a solution to this problem, which is nicely solved by Objective-C 2.0 @compatibility_alias directive. This allows you to write:

    @compatibility_alias NSNumberBool NSNumber;
    

    and have an alias created for NSNumber. KVO works perfectly with it.

    Over the currently accepted answer, this has the great benefit of being type-safe.