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

问题描述 投票:1回答:2

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?

ios swift selector
2个回答
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()

3
投票

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

class Base: NSObject {
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.