预期结果:我创建了一个 block ,将其存储在 NSDictionary 中,将字典传递给 Swift 类,从字典中检索 block ,然后调用 block 。
实际结果:从字典中检索 block 会导致 EXC_BAD_INSTRUCTION。
示例代码 Obj-C View Controller :
- (void)viewDidLoad {
[super viewDidLoad];
void (^completionHandler)() = ^() {
[self printBlahBlah];
};
NSDictionary *dict = @{@"blah":completionHandler};
Nav *nav = [Nav new];
[nav done:dict];
}
-(void)printBlahBlah { NSLog(@"BlahBlah"); }
Nav Swift 类的示例代码:
@objc public class Nav : NSObject {
@objc public func done(dict: NSDictionary){
let block = dict["blah"] as! ()->Void //EXC_BAD_INSTRUCTION
block()
}
}
最佳答案
所以这是可行的:
@objc public class Nav : NSObject {
typealias MyFunBlock = @convention(block) () -> Void;
@objc public func done(dict: NSDictionary){
let block = unsafeBitCast(dict["blah"], BoolBlock.self) as BoolBlock?
block?()
}
}
但是 unsafeBitCast 的文档说:
/// Returns the bits of `x`, interpreted as having type `U`.
///
/// - Warning: Breaks the guarantees of Swift's type system; use
/// with extreme care. There's almost always a better way to do
/// anything.
///
@warn_unused_result
public func unsafeBitCast<T, U>(x: T, _: U.Type) -> U
我觉得我不想用这个。
功劳真的归功于这个人:https://stackoverflow.com/a/28376909/1366911
关于ios - 从 Swift 调用存储在 NSDictionary 中的 Objective-C block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40591550/