In iOS, if you want to start a child thread in the main thread, you can do it in two different ways:
[Nsthread detachnewthreadselector: @selector (mythreadmainmethod:) totarget:self Withobject:nil];
This is the method provided early in the cocoa, so you can use this method on any version of iOS and Mac.
In OS X v10.5 (or later) and iOS, Apple provides a way to allow you to get your thread handle and make it easier for the main thread to control the child threads.
nsthread* myThread = [[Nsthread alloc] Initwithtarget:self
Selector: @selector (mythreadmainmethod:)
Object:nil];
[MyThread start]; Actually create the thread
If you want to stop a child thread, there are two methods:
The first is performed in a child thread:
[Nsthread exit];
The other is performed on the main thread:
[MyThread Cancel];
It should be noted that [Mthread Cancel]; You cannot exit the thread, just mark it as canceled, but the thread does not die. When you execute a loop in a child thread, the loop continues after cancel, and you need to include!mthread.iscancelled in the loop's conditional judgment to determine whether the child thread has been cancel to decide whether to continue the loop.
Here is one of my test demo, you can refer to:
@synthesize Mthread;
-(void) viewdidload
{
[Super Viewdidload];
NSLog (@ "Main thread:%@", [Nsthread CurrentThread]);
Mthread=[[nsthread Alloc] initwithtarget:self selector: @selector (Subthreadmethod) Object:nil];
[Nsthread detachnewthreadselector: @selector (Performmethod) 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) Performonsubthread: (ID) Sender {
Calling a method on a child thread
[Self performselector: @selector (performmethod) onthread:mthread Withobject:nil Waituntildone:no];
}
-(void) performmethod{
NSLog (@ "Performmethod ... thread:%@", [Nsthread CurrentThread]);
}
@end
Transfer from http://www.cnblogs.com/ygm900/archive/2013/05/26/3100076.html
IOS Thread processing sub-threads