gpt4 book ai didi

swift - 在 swift 的通知 block 中引用自己

转载 作者:行者123 更新时间:2023-11-28 07:08:54 25 4
gpt4 key购买 nike

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

我整理了一些示例代码,但似乎无法正常工作,因为我无法访问 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 不是指向类而是指向 block 之类的东西?

最佳答案

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

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 在评论中提到的,这可能与类的一个属性在初始化期间依赖于另一个属性有关

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

关于swift - 在 swift 的通知 block 中引用自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29287808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com