The multithreading methods available on IOS are divided into three types, 1, Nsthread 2, Nsoperation 3, GCD ([Self Performselectorinbackground:sel withobject:id] This method is also a multi-threaded approach in nature, three ways of abstraction is more and more high, the code is more difficult to write more and more simple.
1, Nsthread:
Nsthread are more lightweight than the other two, but need to manage the lifecycle and synchronization of threads themselves, and code is more complex to write than the other two.
Nsthread provides two ways of initializing, one of which is the traditional Init method
NSThread *thread = [[NSThread alloc] initWithTarget:(id) selector:(SEL) object:(id)] [thread start];
At Init, although memory has been allocated for the thread, but the thread does not execute immediately, the advantage of using this method to initialize is obvious, and we can get a Nsthread object that can be easily managed for that thread.
and a different approach
[NSThread detachNewThreadSelector:(SEL) toTarget:(id) withObject:(id)]
Using this method to open a thread, this thread will execute immediately
Look at the code below, we all know that access to the network is a time-consuming operation, in the project we need to show the image obtained from the network when we can use the thread operation
#import "ViewController.h" #define IMAGE_PATH @ "Https://www.baidu.com/img/bdlogo.png" @interface viewcontroller ()@property(Weak,nonatomic)Iboutlet Uiimageview*mimage;@end @implementation viewcontroller - (void) Viewdidload {[SuperViewdidload];additional setup after loading the view, typically from a nib. Nsthread*mthread = [[NsthreadAlloc] Initwithtarget: SelfSelector@selector(downimage:) Object:image_path]; [Mthread start];} - (void) Downimage: (NSString*) imagepath{NSData *imagedata = [[NSData alloc] initwithcontentsofurl:[NsurlUrlwithstring:imagepath]];UIImage*image = [[UIImageAlloc] Initwithdata:imagedata]; [ SelfPerformselectoronmainthread:@selector(setimage:) withobject:image Waituntildone:YES];} - (void) SetImage: (UIImage*) image{[ Self. MimageSetimage:image];} - (void) Didreceivememorywarning {[SuperDidreceivememorywarning];//Dispose of any resources, can be recreated.}@end
Threading operations in iOS (1)