【发布时间】:2016-05-07 02:28:55
【问题描述】:
我正在运行一系列调度,当最后一个调度完成时,我想更改一个按钮的标签。然而,当 UI 组件更改是在主线程之外进行时,更改 swift 是不受欢迎的。有时它会起作用。有时它不会。奇怪的是,如果没有,如果我单击断点图标(无论我是激活所有断点还是禁用,标签都会立即根据需要更改。
@IBAction func runButtonSelected(sender: AnyObject) {
runButton.setTitle("Stop Run", forState: UIControlState.Normal)
isRunning = true
self.run()
}
.
func run() {
let thread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
NSThread.sleepForTimeInterval(1)
dispatch_async(thread, {
NSThread.sleepForTimeInterval(1)
.
.
.
.
var request = Request(URL: NSURL(string: url+params)!, method: "GET", params: "")
request.isRequesting = true
queue.addOperation(request)
request.threadPriority = 0
request.completionBlock = {() -> () in
request.execute()
NSThread.sleepForTimeInterval(2)
}
while request.isRequesting {
if !request.isRequesting {
break
}
}
.
.
.
.
/* visit user profiles based on match results */
for (index, profile) in profiles.enumerate() {
let URL = NSURL(string: "https://www.somewebsite.com/profile/\(profile)")!
let request = Request(URL: URL, method: "GET", params: "")
var contentsOfURL = NSString()
request.isRequesting = true
queue.addOperation(request)
request.threadPriority = 0
request.completionBlock = {() -> () in
request.execute()
}
NSThread.sleepForTimeInterval(1)
}
self.isRunning = false
})
let thread2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(thread2, {
while self.isRunning {
if !self.isRunning {
break
}
}
self.runButton.setTitle("Run", forState: UIControlState.Normal)
})
}
请求.执行
func execute() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = self.method
request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
self.task = session.dataTaskWithRequest(request) {
(data, response, error) in
if error == nil {
do {
.
.
.
.
switch self.statusCode {
case 200:
self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
case 400:
print("400: page not found")
case 404:
print("404: page not found")
case 407:
print("407: failed authenticate proxy credentials")
default:
print("unable to get statusCode")
}
} catch {
print(error)
}
self.isRequesting = false
} else {
print(error)
}
}
self.task.resume()
}
【问题讨论】:
-
也许可以尝试将
dispatch_async(dispatch_get_main_queue(), ...用于线程 2。 -
@I'L'l 这行得通!谢谢。如果您将其作为答案提交,我会将其标记为已回答。
标签: xcode multithreading swift2 nsoperation dispatch-async