Worker Thread iOS

前端 未结 4 924
野性不改
野性不改 2021-01-03 10:20

I want to create a background thread on the iPhone that executes some code every 10msec. But before I get lost in the concurrency programming guide and the threading program

4条回答
  •  星月不相逢
    2021-01-03 11:06

    It is pretty simple and clean if you do it with NSThread. With no need to subclass it.

    - (void)backgroundStuff {
        while (!self.cancelThread) {
            // do your work
            [NSThread sleepForTimeInterval:0.01];
        }
    }
    

    Just an ordinary function. cancelThread is a member variable you declare. Start it with

    [NSThread detachNewThreadSelector:@selector(backgroundStuff) toTarget:self withObject:nil];
    

    and you can cancle the thread anytime with self.cancelThread = true;

提交回复
热议问题