gpt4 book ai didi

ios - NSNotification 不适用于 Swift 翻译(来自 Objective-C)

转载 作者:行者123 更新时间:2023-11-29 02:31:28 25 4
gpt4 key购买 nike

将我的 Objective-C 代码转换为 Swift 后,我​​无法让我的 NSNotifications 工作。在网上搜索了一个小时后,我终于放弃了。考虑以下示例:

func getToUrl(url:String, timeoutInterval:Float) -> Bool {

println("Starting HTTP GET to: \(url)")

// Fire a notification
NSNotificationCenter.defaultCenter().postNotificationName("StartNotification", object: self)

[...]

}

func getJsonFromServer() {

// Add an observer which should fire the method test when desired
NSNotificationCenter.defaultCenter().addObserver(self, selector: "test:", name: "StartNotification", object: self)

// Calls the function
getToUrl("http://www.stackoverflow.com", timeoutInterval: 10)

}

func test(sender: AnyObject) {
println("I am here!")
}

我找不到错误,如果有人能找到,我将不胜感激!

代码运行,但从未调用测试方法。

最佳答案

将 self 更改为 nil(以便听到所有对象)

func getJsonFromServer() {

// Add an observer which should fire the method test when desired
NSNotificationCenter.defaultCenter().addObserver(self, selector: "test:", name: "StartNotification", object: nil)

// Calls the function
getToUrl("http://www.stackoverflow.com", timeoutInterval: 10)

}

关于ios - NSNotification 不适用于 Swift 翻译(来自 Objective-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26816828/

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