如何使用实例方法作为仅需要函数或文字关闭的函数的回调 [英] How to use instance method as callback for function which takes only func or literal closure
问题描述
在 ViewController.swift中,我正在创建此回调:
In "ViewController.swift" I am creating this callback:
func callback(cf:CFNotificationCenter!,
ump:UnsafeMutablePointer<Void>,
cfs:CFString!,
up:UnsafePointer<Void>,
cfd:CFDictionary!) -> Void {
}
使用此观察者:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
self.callback,
"myMESSage",
nil,
CFNotificationSuspensionBehavior.DeliverImmediately)
此编译器错误的结果:
AC函数指针只能由对'func'或字面量闭包的引用构成
"A C function pointer can only be formed from a reference to a 'func' or a literal closure"
推荐答案
回调是指向C函数的指针,在Swift中,您只能将
传递给全局函数或闭包(不会捕获任何状态),
而不是实例方法。
The callback is a pointer to a C function, and in Swift you can pass only a global function or a closure (which does not capture any state), but not an instance method.
因此,这确实可行:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
{ (_, observer, name, _, _) in
print("received notification: \(name)")
},
"myMessage",
nil,
.DeliverImmediately)
但是由于闭包无法捕获上下文,因此您没有直接引用 self
及其属性和实例方法。
例如,您不能添加
But since the closure cannot capture context, you have no direct reference to self
and its properties and instance methods.
For example, you cannot add
self.label.stringValue = "got it"
// error: a C function pointer cannot be formed from a closure that captures context
的闭包形成以更新通知到达时的用户界面。
inside the closure to update the UI when a notification arrived.
有一个解决方案,但是由于
Swift的严格类型系统,它有点复杂。
与 Swift 2-UnsafeMutablePointer< Void>类似到对象,您可以将指向
self
的指针转换为void指针,并将其作为 observer
参数
进行注册,然后将其转换回
回调中的对象指针。
There is a solution, but it is a little bit complicated due to
Swift's strict type system.
Similarly as in Swift 2 - UnsafeMutablePointer<Void> to object, you can convert the pointer to
self
to a void pointer, pass that as the observer
parameter
to the registration, and convert it back to an object pointer in
the callback.
class YourClass {
func callback(name : String) {
print("received notification: \(name)")
}
func registerObserver() {
// Void pointer to `self`:
let observer = UnsafePointer<Void>(Unmanaged.passUnretained(self).toOpaque())
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
observer,
{ (_, observer, name, _, _) -> Void in
// Extract pointer to `self` from void pointer:
let mySelf = Unmanaged<YourClass>.fromOpaque(
COpaquePointer(observer)).takeUnretainedValue()
// Call instance method:
mySelf.callback(name as String)
},
"myMessage",
nil,
.DeliverImmediately)
}
// ...
}
指针是一个未保留的引用,因此必须确保在释放对象之前,必须删除观察者的
。
The pointer is an unretained reference, therefore you must ensure that the observer is removed before the object is deallocated.
Swift 3更新:
class YourClass {
func callback(_ name : String) {
print("received notification: \(name)")
}
func registerObserver() {
// Void pointer to `self`:
let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
observer,
{ (_, observer, name, _, _) -> Void in
if let observer = observer, let name = name {
// Extract pointer to `self` from void pointer:
let mySelf = Unmanaged<YourClass>.fromOpaque(observer).takeUnretainedValue()
// Call instance method:
mySelf.callback(name.rawValue as String)
}
},
"myMessage" as CFString,
nil,
.deliverImmediately)
}
// ...
}
See also How to cast self to UnsafeMutablePointer<Void> type in swift for more information about the "bridging" between object pointers and C pointers.
这篇关于如何使用实例方法作为仅需要函数或文字关闭的函数的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!