1

我希望从 Swift -> Objective C 迁移一些代码,从单元测试开始。

我在传递值类型的模拟函数方面遇到问题:

let initWithTitleBlock : @objc_block (String, String) -> AlertViewMock! = { (title : String, message : String) -> (AlertViewMock!) in
    alert = AlertViewMock(title: title, message: message)
    return alert
}
let initWithTitleImp = imp_implementationWithBlock(unsafeBitCast(initWithTitleBlock, AnyObject.self))
let initWithTitleMethod = class_getInstanceMethod(AlertView.self, Selector("initWithTitle:message:"))
method_setImplementation(initWithTitleMethod, initWithTitleImp)

但我最终在运行时收到以下错误:

-[AlertView copyWithZone:]:无法识别的选择器发送到实例 0x7fef006e4cb0

但是,如果我将传递给块的类型更改为AnyObject或其他一些引用类型,例如NSURL,我能够成功运行新块(除非我无法将对象转换回字符串):

let initWithTitleBlock : @objc_block (AnyObject, AnyObject) -> AlertViewMock! = { (title : AnyObject, message : AnyObject) -> (AlertViewMock!) in ...

我没有标记AlertViewMockcopy。有人可以帮忙解释发生了什么吗?如果我通过NSInteger,我会得到同样的异常:

let initWithTitleBlock : @objc_block (NSInteger, NSInteger) -> AlertViewMock! = { (title : NSInteger, message : NSInteger) -> (AlertViewMock!) in ...
4

0 回答 0