I am learning iOS runloop. Some articles on the net show me code like this:
- (void)memoryIssue {
for (int i = 0; i < 10000; i++) {
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];
[thread setName:thread_name];
[thread start];
[self performSelector:@selector(stopThread) onThread:thread withObject:nil waitUntilDone:YES];
}
}
- (void)runThread {
NSLog(@"current thread = %@", [NSThread currentThread]);
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
static NSMachPort *port;
if (!port) {
port = [NSMachPort port];
}
[runLoop addPort:port forMode:NSDefaultRunLoopMode];
// CFRunLoopRun(); //All right
[runLoop run]; // ⚠️Thread not exit...!
}
- (void)stopThread {
CFRunLoopStop(CFRunLoopGetCurrent());
NSThread *thread = [NSThread currentThread];
[thread cancel];
}
When using CFRunLoopRun()
, it just goes fine. In each for-loop, a thread is created and then exited. However as for [runLoop run]
, the memory keeps growing and finally the app terminates due to "-[NSThread start]: Thread creation failed with error 35"(reaches the upper limit of thread count?)
**My question:
What is the difference between
-run()
andCFRunLoopRun()
? I thought the former is just a wrapper of the latter.The code seems to intend to show the right way to exit a thread. Is it practical in real-life developing?**