Остановить NSRunLoop
У меня есть соединение в потоке, поэтому я добавляю его в цикл выполнения, чтобы получить все данные:
[[NSRunLoop currentRunLoop] run];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
Но я не могу найти способ остановить это
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if([NSRunLoop currentRunLoop]){
[[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget:self];
}
[connection cancel];
}
Как я могу остановить этот цикл?
2 ответа
Вы можете остановить цикл запуска с помощью Core Fundation API:
CFRunLoopStop(CFRunLoopGetCurrent());
Вот пример, когда RunLoop используется в сочетании с выделенным потоком.
class MyClass {
private weak var cancellableThread: Thread? // Need to be `weak` as we want thread to delloc after it's job is done.
// Say your UI allow user to start / stop some job.
func handleStartStopButtonClick() {
if let thread = cancellableThread {
print("Will inform thread about job end.")
thread.threadDictionary["my-status-key"] = true
} else {
print("Will start threаd.")
cancellableThread = startCancellableRunLoop()
}
}
func startCancellableRunLoop() -> Thread {
let thread = Thread() {
let timer = Timer(timeInterval: 2, repeats: true) { _ in
print("Timer is fired: \(Date().timeIntervalSinceReferenceDate)")
if let statusValue = Thread.current.threadDictionary["my-status-key"] as? Bool, statusValue == true {
CFRunLoopStop(RunLoop.current.getCFRunLoop())
}
}
let rl = RunLoop.current
let rlMode = RunLoop.Mode.default
rl.add(timer, forMode: rlMode)
let status = rl.run(mode: rlMode, before: Date.distantFuture)
print("Job is completed: status=\(status)")
}
thread.start()
return thread
}
}