我创建了一个MyService
类,使它像这样单身:
标头:
@interface MyService : NSObject
+(MyService *)sharedInstance;
@end
实施:
@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;
}
...
@end
如上所示,我在
dispatch_queue_t queue
类中定义了一个私有变量MyService
。在另一个类中,我尝试通过以下方式访问此私有变量:
dispatch_queue_t queue = [[MyService sharedInstance] valueForKey:@"queue"];
但是上面的代码会导致运行时错误:
caught "NSUnknownKeyException", "[<MyService 0x7a068440> valueForUndefinedKey:]: this class is not key value coding-compliant for the key queue."
为什么会出现此错误? (我在另一个地方使用相同的方法来访问另一个类的BOOL私有变量,并且在那里工作正常)
最佳答案
正如我昨天(今天?)向您解释的那样,键值编码形成了键的访问者选择器。您没有选择器要执行的访问器方法。 (有关协议:它可以直接访问ivars,请参见+accessInstanceVariablesDirectly
,但您不想这样做。)
使其成为财产。这将自动添加访问器。或手动实现访问器。
关于ios - 使用“valueForKey:”访问私有(private)变量,但出现运行时错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38020056/