Stop an NSRunLoop
Asked Answered
M

2

10

I have a connection in a thread, so I add it to the run loop to get all data:

  [[NSRunLoop currentRunLoop] run];
  [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

But I can't find any way to stop it

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if([NSRunLoop currentRunLoop]){
        [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget:self];
    }
    [connection cancel];
}

How can I stop this loop?

Moultrie answered 25/4, 2013 at 10:5 Comment(0)
L
18

You can stop the runloop by Core Fundation API :

CFRunLoopStop(CFRunLoopGetCurrent());
Lucifer answered 28/6, 2013 at 15:29 Comment(3)
While I've got this to work, I'm not sure I understand how this really works? Does a Core Foundation Run Loop method terminate a NSRunloop?Displayed
NSRunLoop and CFRunLoopRef are two interfaces for the same underlying structure, @Displayed (although they are not "toll-free bridged" as it's called). So [NSRunLoop currentRunLoop] and CFRunLoopGetCurrent() essentially provide you with access to the same thing, but only the CF API has a "stop" button.Ijssel
Can be also written as CFRunLoopStop(RunLoop.current.getCFRunLoop()).Hutchison
H
0

Here is an example when RunLoop used in conjunction with a dedicated Thread.

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
  }

}
Hutchison answered 18/2, 2023 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.