在 swift 的通知块中引用自己

Referencing self in notification block in swift

因为我厌倦了拼错选择器名称,所以我想我会尝试用块而不是选择器来做一些通知。

我整理了一些示例代码,但似乎无法正常工作,因为我无法访问 self

var currentString : String?

// Type alias the notificaitonBlock
typealias notificationBlock = (NSNotification?) -> ()

// in this case note is an NSNotification?
let strNotification : notificationBlock = { notification in
    if let msg = notification?.object as? String {
        self.currentString = msg
    }
}

假设此代码有效,我将注册它:

nc.addObserverForName(UIDeviceOrientationDidChangeNotification, 
    object: self, 
    queue: NSOperationQueue.currentQueue(), 
    usingBlock: strNotification)

Xcode 给我以下错误:

NotificationTests.swift:49:4: 'NotificationTests -> () -> NotificationTests' 没有名为 'currentString'

的成员

这意味着 self 没有指向 class 而是块或其他东西?

您可以在为块使用实例变量时使用它:

lazy var block: (NSNotification?) -> () = { notification in
    if let msg = notification?.object as? String {
        self.currentString = msg
    }
}

或在方法调用中:

func registerObeserver() {
    NSNotificationCenter.defaultCenter().addObserverForName(UIDeviceOrientationDidChangeNotification, object: self, queue: NSOperationQueue.currentQueue(), { notification in
        if let msg = notification?.object as? String {
            self.currentString = msg
        }
    })
}

正如 Martin R 在评论中提到的,这可能与 class 中的一个 属性 有关,这取决于初始化期间的另一个

与 javascript 中的不同,self 不会在闭包内发生变化