2016-11-16 65 views
3

我不得不a trick帮助测试UIAlertController,在斯威夫特2.X工作:如何在Swift 3中将__NSMallocBlock__转换为其基础类型?

extension UIAlertController { 

    typealias AlertHandler = @convention(block) (UIAlertAction) -> Void 

    func tapButtonAtIndex(index: Int) { 
     let block = actions[index].valueForKey("handler") 
     let handler = unsafeBitCast(block, AlertHandler.self) 

     handler(actions[index]) 
    } 

} 

这不履行斯威夫特3.X与fatal error: can't unsafeBitCast between types of different sizes,这诱惑我相信有可能是一种方法,使演员的工作。任何人都可以弄明白吗?

回答

7

发现,在斯威夫特3.0.1

extension UIAlertController { 

    typealias AlertHandler = @convention(block) (UIAlertAction) -> Void 

    func tapButton(atIndex index: Int) { 
     if let block = actions[index].value(forKey: "handler") { 
      let blockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(block as AnyObject).toOpaque()) 
      let handler = unsafeBitCast(blockPtr, to: AlertHandler.self) 
      handler(actions[index]) 
     } 
    } 

} 

有效的解决方案(最初,block值实际块,而不是一个指针块,你显然不能转换为指针,以AlertHandler

+0

非常有帮助,谢谢! – xytor

0

如果您的UIAlertController是一个操作表,您可以在执行处理程序之前修改Robert的答案以关闭UIAlertController。

驳回(动画:真,完成:{()中的处理程序(self.actions [指数])})

我用此扩展的测试和无该变形例我的断言为呈现视图控制器进行故障。

相关问题