Makio
Makio

Reputation: 483

Stop an NSRunLoop

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?

Upvotes: 10

Views: 8257

Answers (2)

Vlad
Vlad

Reputation: 6732

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
  }

}

Upvotes: 0

hrchen
hrchen

Reputation: 1223

You can stop the runloop by Core Fundation API :

CFRunLoopStop(CFRunLoopGetCurrent());

Upvotes: 18

Related Questions