how to stop nsthread

前端 未结 4 1709
悲哀的现实
悲哀的现实 2021-01-06 18:57

I am using a thread to update messages in background in my application. The thread is started in my messages class.

Messages.m

ti         


        
相关标签:
4条回答
  • 2021-01-06 19:16

    Use [NSThread exit]; or [NSThread cancel];

    0 讨论(0)
  • 2021-01-06 19:17
    [NSThread exit];
    

    Have you checked this method of NSThread class.

    0 讨论(0)
  • 2021-01-06 19:19

    ( I am assuming here that you create an instance of Messages somewhere else in the program )

    According to your provided code you are creating a new Messages instance as part of your sign out process ( which starts a new thread ), canceling that new thread ( -cancel is a proper way to stop a thread -- if your thread method follows the considerations listed in the documentation ), then releasing your ( extra? ) Messages instance. At this point your original Messages instance is still around, and the thread from that is still running.

    If you want the thread to stop when the instance of the class is deallocated, you probably should take care of that in a -dealloc method on Messages and make sure your original Messages instance is released at the proper time.

    0 讨论(0)
  • 2021-01-06 19:22

    [timerThread cancel] doesn't stop thread, it just marks it as cancelled. I presume that your startTimerThread: performs some sort of infinite loop. You have to check isCancelled in this loop periodically and if it's YES you should perform some clean up and break from this loop.

    BTW if you don't perform updates frequently it is more convenient to run NSTimer in main thread and detach new thread on callbacks (like [self performSelectorInBackground:@selector(updateMessages:) withObject:whatever]) or start an instance of NSOperation.

    0 讨论(0)
提交回复
热议问题