In IOS, if you want to enable a subthread in the main thread, you can use either of the following methods:
[Cpp]
[NSThread detachNewThreadSelector: @ selector (myThreadMainMethod :) toTarget: self withObject: nil];
This method was provided earlier in cocoa, so you can call this method on any version of ios or mac.
In OS X v10.5 (or later) and IOS, Apple provides another method that allows you to obtain your thread handle and more conveniently allow the main thread to control the sub-thread.
[Cpp]
NSThread * myThread = [[NSThread alloc] initWithTarget: self
Selector: @ selector (myThreadMainMethod :)
Object: nil];
[MyThread start]; // Actually create the thread
To stop a sub-thread, you can use either of the following methods:
First, it is executed in the Child thread:
[Cpp]
[NSThread exit];
The other is executed in the main thread:
[Cpp]
[MyThread cancel];
Note that [mThread cancel]; The exit thread cannot be marked as canceled, but the thread does not die. If you have executed a loop in the Child thread, after cancel is added, the loop continues. You need to add it to the condition judgment of the loop! MThread. isCancelled to determine whether the Sub-thread has been cancel to determine whether to continue the loop.
The following is a test demo of mine. For details, refer:
[Cpp]
@ Synthesize mThread;
-(Void) viewDidLoad
{
[Super viewDidLoad];
NSLog (@ "main thread: % @", [NSThread currentThread]);
MThread = [[NSThread alloc] initWithTarget: self selector: @ selector (subThreadMethod) object: nil];
[NSThread detachNewThreadSelector: @ selector (optional parameter hod) toTarget: self withObject: nil];
}
-(Void) subThreadMethod {
Int I = 1;
While (I ++> 0 &&! [[NSThread currentThread] isCancelled]) {
NSLog (@ "subthread I: % d, thread: % @", I, [NSThread currentThread]);
}
}
-(IBAction) startThread :( id) sender {
NSLog (@ "startThread ....");
[MThread start];
}
-(IBAction) stopThread :( id) sender {
NSLog (@ "mThread. isCancelled: % d", mThread. isCancelled );
If (! MThread. isCancelled ){
[MThread cancel];
// [MThread exit]; // exit is a class method and cannot be used on an object.
}
}
-(IBAction) mongomonsubthread :( id) sender {
// Call the method in the subthread
[Self defined mselector: @ selector (specified parameter hod) onThread: mThread withObject: nil waitUntilDone: NO];
}
-(Void) invalid parameter hod {
NSLog (@ "zookeeper hod... thread: % @", [NSThread currentThread]);
}
@ End