来自 Using Swift with Cocoa and Objective-C - Working with Cocoa Frameworks :
Swift automatically converts some Objective-C types to Swift types, and some Swift types to Objective-C types.
但在某些情况下,自动桥接是不可取的,例如性能问题或桥接实现中的错误。
如何在特定情况下禁用此行为?例如。用于特定语句或特定类。
最佳答案
我希望有一个 NS_DO_NOT_BRIDGE_FOR_SWIFT
宏,但遗憾的是,它不存在。浏览 Swift 的源代码,我无法找到禁用桥接的神奇宏。下面的回答很啰嗦。它依赖于 2 个事实:
- 核心基础类型(即
CF*
)未桥接到 Swift 中 - Core Foundation (
CF*
) 和 Cocoa (NS*
) 类型之间有免费桥接
让我们看一个例子。首先,Objective-C 方面:
// MyClass.h
@interface MyClass : NSObject
NS_ASSUME_NONNULL_BEGIN
- (NSArray *) randomNumbers NS_SWIFT_UNAVAILABLE(""); // mark this method as unavailable in Swift
- (CFArrayRef) cfRandomNumbers NS_REFINED_FOR_SWIFT; // tell the compiler that you have a refined version for Swift
NS_ASSUME_NONNULL_END
@end
// MyClass.m
#import "MyClass.h"
@implementation MyClass
- (NSArray *) randomNumbers {
return @[ @1, @2, @3 ];
}
- (CFArrayRef) cfRandomNumbers {
return CFBridgingRetain([self randomNumbers]); // toll-free
}
@end
swift 方面
extension MyClass {
// Even though we marked `randomNumbers` as unavailable in Swift, we can't
// use the same signature. Must name it something else.
func objcRandomNumbers() -> NSArray {
// Methods marked with NS_REFINED_FOR_SWIFT pick up
// double-underscore prefix in their names
return __cfRandomNumbers().takeUnretainedValue() as NSArray
}
}
let obj = MyClass()
let arr = obj.objcRandomNumbers() // no bridging here
好处是一切都被记录下来,因此是“官方的”。您可以通过 Profiler 运行代码来检查是否发生了桥接。
关于objective-c - 在某些情况下禁用自动桥接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022733/