当@objc和@nonobjc迅速写在方法和变量之前吗? [英] When @objc and @nonobjc write before method and variable in swift?

查看:464
本文介绍了当@objc和@nonobjc迅速写在方法和变量之前吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在类的扩展中声明静态参数时,我必须在像这样的变量之前写@nonobjc

When I declare static parameter in extension of class then I have to write @nonobjc before variable like

 @nonobjc static let test = "test"

有时我必须在方法之前编写@objc,所以在Swift中@objc和@nonobjc的用途是什么.

and sometimes i have to write @objc before method, so what is use of @objc and @nonobjc in swift.

有人可以帮助我解决这个问题吗?

can anyone help me for this problem ?

推荐答案

This is explained in the Apple's official documentation about Objective-C - Swift interoperability:

在Swift类上使用@objc(name)属性时,该类为 可以在Objective-C中使用,没有任何命名空间.因此, 此属性在迁移可归档文件时也很有用 Swift的Objective-C类.由于存档对象存储的名称 他们在存档中的类,则应使用@objc(name)属性 指定与您的Objective-C类相同的名称,以便更老 新的Swift类可以取消归档文件.

When you use the @objc(name) attribute on a Swift class, the class is made available in Objective-C without any namespacing. As a result, this attribute can also be useful when migrating an archivable Objective-C class to Swift. Because archived objects store the name of their class in the archive, you should use the @objc(name) attribute to specify the same name as your Objective-C class so that older archives can be unarchived by your new Swift class.

相反,Swift还提供了@nonobjc属性,该属性使 Swift声明在Objective-C中不可用.你可以用它来 解决桥接方法的圆度问题,并允许重载 Objective-C导入的类的方法.如果是Objective-C方法 被无法在其中表示的Swift方法覆盖 Objective-C(例如,通过将参数指定为变量)可以 方法必须标记为@nonobjc.

Conversely, Swift also provides the @nonobjc attribute, which makes a Swift declaration unavailable in Objective-C. You can use it to resolve circularity for bridging methods and to allow overloading of methods for classes imported by Objective-C. If an Objective-C method is overridden by a Swift method that cannot be represented in Objective-C, such as by specifying a parameter to be a variable, that method must be marked @nonobjc.

总而言之,当您要将Swift属性公开给Objective-C而没有命名空间时,请使用@objc.如果要保持属性仅在Swift代码中可用和访问,请使用@nonobjc.

To summarize, use @objc when you want to expose a Swift attribute to Objective-C without a namespace . Use @nonobjc if you want to keep the attribute available and accessible only in Swift code.

这篇关于当@objc和@nonobjc迅速写在方法和变量之前吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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