从Swift调用存储在NSDictionary中的Objective-C块

时间:2016-11-14 14:51:43

标签: ios objective-c swift

预期结果:我创建一个块,将其存储在NSDictionary中,将字典传递给Swift类,从字典中检索块,然后调用块。

实际结果:从字典中检索块会产生EXC_BAD_INSTRUCTION。

示例代码Obj-C视图控制器:

- (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()
    }
}

2 个答案:

答案 0 :(得分:2)

这样可行:

@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

答案 1 :(得分:1)

我认为正在发生的是块在Swift中使用之前就已经发布了。通过将其复制到集合中进行修复...

// ...
NSDictionary *dict = @{@"blah":[completionHandler copy]};
// ...