the Performselectoronmainthread and Performselectorinbackground of the NSObject class enable simple multithreaded programming techniques
1,-(void) Performselectorinbackground: (SEL) Aselector withobject: (ID) arg
Creates a thread that executes on a child thread, Aselector represents the newly created thread, and ARG is the parameter passed in
2,-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) wait;
The function of this method is to execute the developed method (code block) in the main thread.
Parameters:
@selector is to define the method that we want to execute.
Withobject:arg defines the parameter object that is passed in when we execute the method. The type is the ID. (We can pass in any parameter)
WAITUNTILDONE:YES Specifies whether the current thread will be blocked until the main thread finishes executing the block of code we have made.
Attention:
1. The Waituntildone:yes parameter is not valid when the current thread is the main path.
2. The method, no return value
3. This method is mainly used to modify the state of the page UI with the main thread.
Sample code:
-(void) viewdidload{ [Super viewdidload];//do no additional setup after loading the view, typically from a nib. _label=[[uilabel Alloc] Initwithframe:cgrectmake (max, Max, Max)]; _label.textcolor=[uicolor Redcolor]; [Email protected] "123"; [Self.view Addsubview:_label]; [Self Performselectorinbackground: @selector (backwork) withobject:nil];} -(void) backwork{ NSLog (@ "The thread is%@", [Nsthread CurrentThread]); Sleep (2); [Self Performselectoronmainthread: @selector (mainwork) Withobject:nil waituntildone:no];} -(void) mainwork{ NSLog (@ "The main thread is%@", [Nsthread CurrentThread]); [Email protected] "456"; _label.textcolor=[uicolor Greencolor];}
Execution Result:
2014-08-19 11:03:59.101 testapp[1848:3107] The thread is <nsthread:0x8c504a0>{name = (null), num = 2}
2014-08-19 11:04:01.103 testapp[1848:60b] The main thread is <nsthread:0x8c444c0>{name = (null), num = 1}