IBAction 上的键值编码合规性错误

Key value coding compliancy error on IBAction

免责声明:请忽略使用此功能的生产应用可能会或可能不会通过审核的事实。我只是想让这个概念发挥作用。这是我要执行的代码,我(现在)要做的就是初始化四个常量,第三个常量有困难。

let app = UIApplication.shared
let statusBar = app.value(forKey: "statusBar") as AnyObject
let foregroundView = statusBar.value(forKey: "foregroundView") as AnyObject
let subviews = Array(foregroundView.subviews)

报错:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_SwiftValue 0x170087850> valueForUndefinedKey:]: this class is not key value coding-compliant for the key foregroundView.'

请注意,与应用 运行 时发生的大多数其他键值合规性错误不同,我的错误仅在执行包含四行代码的 IBAction(由 UIButton 触发)时发生。

作为参考,我正在尝试实现 this post 在 Objective-C 中描述的内容。我是 Swift 的新手,但我认为我 运行 对它的描述是正确的。

整个func在这里:

@IBAction func getSignal(_ sender: UIButton) {

    let app = UIApplication.shared
    let statusBar = app.value(forKey: "statusBar") as AnyObject
    let foregroundView = statusBar.value(forKey: "foregroundView") as AnyObject
    let subviews = Array(foregroundView.subviews)
    var dataNetworkItemView: UIView?
    for subview in subviews {
        if (subview as AnyObject).isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
            dataNetworkItemView = subview
            break
        }
    }
    let signalStrength = (dataNetworkItemView?.value(forKey: "signalStrengthRaw") as? NSString)?.intValue
    print("signal \(signalStrength)")
}

我从原始代码块转换而来,这里:

    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"]     valueForKey:@"foregroundView"] subviews];
    NSString *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]])
        {
            dataNetworkItemView = subview;
            break;
        }
    }
    int signalStrength = [[dataNetworkItemView valueForKey:@"signalStrengthRaw"] intValue];
    NSLog(@"signal %d", signalStrength);

没有编译时错误或警告,我不知道如何继续。谢谢。

工作 Xcode 8 测试版,Swift 3.0 代码:

let app = UIApplication.shared
let statusBar = app().value(forKey: "statusBar")! as AnyObject
let foregroundView = statusBar.value(forKey: "foregroundView")! as AnyObject
let subviews = Array(foregroundView.subviews)
var dataNetworkItemView: UIView?
for subview in subviews {
    if (subview as AnyObject).isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
        dataNetworkItemView = subview
        break
    }
}
let signalStrength = (dataNetworkItemView?.value(forKey: "signalStrengthRaw") as? NSString)?.intValue
print("signal \(signalStrength)")

OP 使用的是 Xcode 8 GM,因此需要将 app() 更改为 app

let statusBar = app.value(forKey: "statusBar")! as AnyObject