如何在 Swift 中进行弱链接? [英] How do I do weak linking in Swift?

查看:30
本文介绍了如何在 Swift 中进行弱链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Objective-C 中,如果我想使用只存在于新版本 iOS 中的特定类,我会这样做:

In Objective-C, if I wanted to use a specific class that's only present in a new version of iOS, I would do something like this:

if( [UIBlurEffect class] ) {
  // do something with UIBlurEffect
}
else {
  // gracefully fallback to old behavior
}

然而,等效的 Swift:

However, the equivalent Swift:

if UIBlurEffect.self != nil {
  let blur: UIBlurEffect = UIBlurEffect(...)
  // ...
else {
  // ...
}

// also occurs with NSClassFromString("UIBlurEffect")

没有相同的功能.

如果在 NSNewFeature 可用的环境中运行,一切都很好.但是如果没有定义类,启动应用程序时会出现链接错误:

If run on an environment where NSNewFeature is available, everything is fine. But if the class isn't defined, I get a link error when starting the application:

dyld: Symbol not found: _OBJC_CLASS_$_UIBlurEffect

那么如何在 Swift 中做弱链接呢?

So how do I do weak linking in Swift?

编辑 添加了 UIBlurEffect 作为具体示例.

Edit Added UIBlurEffect as specific example.

推荐答案

看来我已经知道你能做什么了

Seems like I've figured out what you can do

  1. 我使用 NSClassFromString() 来检查类是否在设备上可用,即

  1. I used NSClassFromString() to check if class is available on device, i.e.

if NSClassFromString("UIBlurEffect") {
    let blur = UIBlurEffect(...)
    //...
}
else {
    //...
}

  • 需要使 UIKit.framework(或其他相应的框架)可选.如果您在 XCode6-BetaX 中创建基于 Swift 的应用程序,所有框架都不会显式添加到链接构建阶段,因此您需要转到目标设置,将 UIKit.framework 添加为链接框架(在 'Link Binary With Libraries' 部分)并将其状态更改为 Optional.这一步成功了,我已经成功地运行了特定于版本的代码.

  • It's needed to make UIKit.framework (or another corresponding framework) optional. If you create Swift-based application in XCode6-BetaX, all the frameworks wouldn't be explicitly added to the link build phase so you need to go to your target settings, add UIKit.framework as a linked framework (in 'Link Binary With Libraries' section) and to change its status to Optional. This step does the trick and I've managed to run version specific code without a problem.

    更新:您不再需要将其设为可选,因为 Xcode 6 beta 6(通过 @user102008)

    Update: You don't need to make it optional anymore, since Xcode 6 beta 6 (via @user102008)

    更新 2:您实际上无法执行隐式 if 语句检查 nil(自 Xcode 6 Beta 5 起).你需要这样断言:

    Update 2: You can't actually perform implicit if statement checks for nil (since Xcode 6 Beta 5). You need to assert it like that:

        if NSClassFromString("UIBlurEffect") != nil {
            let blur = UIBlurEffect(...)
            //...
        }
        else {
            //...
        }
    

    (来自@daniel-galasko)

    (via @daniel-galasko)

    这篇关于如何在 Swift 中进行弱链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆