Leem.fin Leem.fin - 2 years ago 47
Objective-C Question

use "valueForKey:" to access private variable but got run-time error

I created a

class, I made it a singleton like this:

header :

@interface MyService : NSObject
+(MyService *)sharedInstance;


@implementation MyService {
dispatch_queue_t queue;

+ (VADispatchQueue *)sharedInstance {
static MyService *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyService alloc] init];
queue = dispatch_queue_create("my.custom.queue", NULL);
return sharedInstance;


As you see above, I defined a private variable
dispatch_queue_t queue

In another class, I try to access this private variable by:

dispatch_queue_t queue = [[MyService sharedInstance] valueForKey:@"queue"];

But above code causes run-time error:

caught "NSUnknownKeyException", "[<MyService 0x7a068440> valueForUndefinedKey:]: this class is not key value coding-compliant for the key queue."

Why I get this error? (I have another place use the same way to access a BOOL private variable of another class and it works fine there)

Answer Source

As I explained you yesterday (today?) key-value coding forms accessor selectors from keys. You do not have accessor methods to be executed o the selector. (For the protocol: It can access ivars directly, see +accessInstanceVariablesDirectly, but you do not want to do that.)

Make it a property. This will automatically add accessors. Or implement accessors manually.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download