ios - 使用 "valueForKey:"访问私有(private)变量但出现运行时错误

标签 ios objective-c

我创建了一个 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

正如您在上面看到的,我在 MyService 类中定义了一个 private 变量 dispatch_queue_t queue

在另一个类中,我尝试通过以下方式访问这个私有(private)变量:

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 私有(private)变量并且在那里工作正常)

最佳答案

正如我昨天(今天?)向您解释的那样,键值编码从键中形成访问器选择器。您没有要在选择器上执行的访问器方法。 (对于协议(protocol):它可以直接访问ivars,参见+accessInstanceVariablesDirectly,但你不想这样做。)

让它成为一个属性。这将自动添加访问器。或者手动实现访问器。

关于ios - 使用 "valueForKey:"访问私有(private)变量但出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38020056/

相关文章:

ios - Xcode 6.4 : OS X and iOS Targets, Cordova

ios - UIImageView 并不总是为模板图像着色

iphone - 获得精确的时间戳和时间差异

iOS 关闭一个 View Controller 并在不显示基本 View Controller 的情况下呈现另一个 View Controller

ios - 使用 Storyboard 更改 segue 端点

ios - 从跨多个 View Controller 的 TableView 单元显示警报 Controller

php - Instagram API - 无法获取已接受关注请求的私有(private)用户的媒体

ios - 当我想使用 CoreData 保存数据时出现错误,例如 The Model used to Open the store is incompatible with the one used to create the store

iphone - UITableView只有向上滚动后才会显示

objective-c - sqlite fts 不适用于临时版本的应用程序,但仅适用于从 xcode 启动的版本