代码之家  ›  专栏  ›  技术社区  ›  psychotik

弱链接-检查类是否存在并使用该类

  •  84
  • psychotik  · 技术社区  · 16 年前

    我正在尝试创建一个通用的iPhone应用程序,但它使用的类只在更新版本的SDK中定义。框架存在于较旧的系统上,但框架中定义的类不存在。

    我知道我想使用某种弱链接,但是我能找到的任何文档都会讨论函数存在性的运行时检查-如何检查类的存在?

    2 回复  |  直到 7 年前
        1
  •  160
  •   Oliver Maksimovic    7 年前

    TLDR

    电流:

    • 迅捷 : if #available(iOS 9, *)
    • Obj-C,IOS : if (@available(iOS 11.0, *))
    • OX-C,OSX : if (NSClassFromString(@"UIAlertController"))

    遗产:

    • Swift(2.0之前的版本) : if objc_getClass("UIAlertController")
    • obj-c,iOS(4.2之前的版本) : if(nsClassFromString(@“uiAlertController”))
    • obj-c,iOS(11.0之前的版本) : if ([UIAlertController class])

    斯威夫特2 +

    虽然历史上建议检查功能(或类的存在)而不是特定的操作系统版本,但由于引入了 availability checking .

    用这种方式代替:

    if #available(iOS 9, *) {
        // You can use UIStackView here with no errors
        let stackView = UIStackView(...)
    } else {
        // Attempting to use UIStackView here will cause a compiler error
        let tableView = UITableView(...)
    }
    

    注: 如果你尝试使用 objc_getClass() ,将出现以下错误:

    ___'uiAlertController'仅在iOS 8.0或更新版本上可用。


    以前版本的swift

    if objc_getClass("UIAlertController") != nil {
        let alert = UIAlertController(...)
    } else {
        let alert = UIAlertView(...)
    }
    

    注意 ObjcGETCH类() is more reliable than NSClassFromString() or objc_lookUpClass() .


    目标C,IOS 4.2+

    if ([SomeClass class]) {
        // class exists
        SomeClass *instance = [[SomeClass alloc] init];
    } else {
        // class doesn't exist
    }
    

    code007's answer for more details .


    OS X或以前版本的iOS

    Class klass = NSClassFromString(@"SomeClass");
    if (klass) {
        // class exists
        id instance = [[klass alloc] init];
    } else {
        // class doesn't exist
    }
    

    使用 NSClassFromString() . 如果它回来 nil 类不存在,否则将返回可使用的类对象。

    这是苹果公司在 this document :

    […]您的代码将测试 类的存在使用 nsclasFromsString()。 哪个会回来 如果[类]是有效的类对象 如果不存在,则为零。如果 类确实存在,您的代码可以使用它 […]

        2
  •  69
  •   Cœur Gustavo Armenta    9 年前

    对于使用iOS 4.2或更高版本的基本SDK的新项目,有一种新的推荐方法,即使用nsObject类方法检查运行时弱链接类的可用性。即

    if ([UIPrintInteractionController class]) {
        // Create an instance of the class and use it.
    } else {
        // Alternate code path to follow when the
        // class is not available.
    }
    

    来源: https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/cross_development/Using/using.html#//apple_ref/doc/uid/20002000-SW3

    此机制使用ns_class_available宏,该宏可用于 iOS中的框架(请注意,有些框架可能还不支持可用的ns_类-请查看iOS发行说明中的相关内容)。可能还需要额外的设置配置,这些配置可以在上面提供的Apple文档链接中读取,但是,这种方法的优点是您可以进行静态类型检查。