iOS NSThreadGCD 線程與隊列(一)
2019-11-06 09:43:18
供稿:網友
//// NSThreadVController.m// ZM_NSThreadGCD//// Created by ZM on 2015/2/9.// Copyright ? 2015年ZM. All rights reserved.//#import"NSThreadVController.h"@interfaceNSThreadVController (){ UILabel *my_label;}@end@implementationNSThreadVController- (void)viewDidLoad{ [superviewDidLoad]; self.title= @"NSThreadVC"; my_label= [[UILabelalloc]initWithFrame:CGRectMake(80,80,150,60)]; my_label.backgroundColor=[UIColorcyanColor]; my_label.text=@"幸福每一天"; my_label.font=[UIFontsystemFontOfSize:15]; my_label.textAlignment=NSTextAlignmentCenter; [self.viewaddSubview:my_label]; [selfaddBtnTitle:@"開辟分線程"frame:CGRectMake(10, 200,200,35)Tag:111];}- (void)myBtnClick:(UIButton*)Btn{ NSDictionary *params = @{@"key1":@"value1", @"key2":@"value2"}; //開辟分線程 [NSThreaddetachNewThreadSelector:@selector(newThread:)toTarget:selfwithObject:params];}//分線程-(void)newThread:(NSMutableDictionary*)dic{ //創建線程 //判斷BOOL量 NSThread *thread = [NSThreadcurrentThread]; BOOL isMainThread = [threadisMainThread]; NSLog(@"---> thread = %d",isMainThread); NSLog(@"---> dic = %@ /n ",dic); //創建主線程 //去網絡請求獲取數據請求完成 必須要回到主線程刷新數據 [selfperformSelectorOnMainThread:@selector(mainThread:)withObject:@"在主線程刷新數據"waitUntilDone:YES]; // //1.直接在開辟的線程中可以刷新數據// my_label.text = [dic objectForKey:@"key1"];//// //2.無論在分線程或者主線程中再開辟一個分線程:都不能刷新數據// [NSThread detachNewThreadSelector:@selector(againNewThread_Two:) toTarget:self withObject:@{@"labelText": @"label"} ]; }//主線程-(void)mainThread:(NSString*)str{ //1.主線程刷新數據 NSLog(@"---> str: %@",str); my_label.text= str; //2.無論在分線程或者主線程中再開辟一個分線程:都不能刷新數據// [NSThread detachNewThreadSelector:@selector(againNewThread_Two:) toTarget:self withObject:@{@"labelText": @"label"} ]; }//在線程中:再開辟一個分線程-(void)againNewThread_Two:(NSMutableDictionary*)dic{ NSString *str= [dic objectForKey:@"label"]; NSLog(@"---> my_label.text: %@ /n ",str); my_label.text= str;}@end