UIImageWriteToSavedPhotosAlbum中的Swift Selector无法识别,为什么?

时间:2017-09-25 14:58:01

标签: ios swift selector

iOS API函数UIImageWriteToSavedPhotosAlbum将选择器作为一个细分:

func UIImageWriteToSavedPhotosAlbum(_ image: UIImage, 
                              _ completionTarget: Any?, 
                              _ completionSelector: Selector?, 
                              _ contextInfo: UnsafeMutableRawPointer?)

https://developer.apple.com/documentation/uikit/1619125-uiimagewritetosavedphotosalbum

然而,在swift中,当我调用此函数时,选择器永远不会被识别:

class Base {
   func save_image(img:UIImage) {
        UIImageWriteToSavedPhotosAlbum(img, self, Selector("image:didFinishSavingWithError:contextInfo:"), nil)
        // I also tried this:
        // UIImageWriteToSavedPhotosAlbum(img, self, #selector(image(_:didFinishSavingWithError:contextInfo:))
    }

   @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        print("Photo Saved Successfully")
    }
}

class Child:Base {
}

// This is how I call the save_image function:
let child = Child()
child.save_image()

正如您所看到的,我尝试从签名和字符串构造选择器,但都不起作用。我总是在运行时遇到这个错误:

'XXX.Child' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector ......

这里发生了什么?我想知道这是因为swift没有看到来自Child类的方法,因为该方法是从Base类继承的?

如何成功传递选择器?

我读过的相关问题:

@selector() in Swift?

3 个答案:

答案 0 :(得分:4)

为您的选择器提供一些指导,以帮助它找到正确的功能:

class Base {
    func save_image(img:UIImage) {
        UIImageWriteToSavedPhotosAlbum(img, self, #selector(Base.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }

    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        print("Photo Saved Successfully")
    }
}

class Child:Base {
}

// This is how I call the save_image function:
let child = Child()
child.save_image()

答案 1 :(得分:4)

methodSignatureForSelector是NSObject的方法。 所以,你需要继承NSObject类。

class Base: NSObject {
    ...
}

答案 2 :(得分:1)

经过所有尝试,我发现关键的事情是:

  1. 方法签名必须匹配(很多答案都涵盖了该问题)
  2. 不要将参数传递到错误的位置,我的失败之一是,我将target传递给了contextInfo
  3. 也许仅在Swift中,实现回调函数的类必须继承自NSObject