iOS NSThreadGCD 线程与队列(一)

//
//  NSThreadVController.m
//  ZM_NSThreadGCD
//
//  Created by ZM on 2015/2/9.
//  Copyright © 2015 ZM. All rights reserved.
//

#import "NSThreadVController.h"

@interface NSThreadVController ()
{
   
UILabel *my_label;
}
@end

@implementation NSThreadVController

- (
void )viewDidLoad
{
    [
super viewDidLoad ];
   
self . title = @"NSThreadVC" ;

   
my_label = [[ UILabel alloc ] initWithFrame : CGRectMake ( 80 , 80 , 150 , 60 )];
   
my_label . backgroundColor =[ UIColor cyanColor ];
   
my_label . text = @" 幸福每一天 " ;
   
my_label . font =[ UIFont systemFontOfSize : 15 ];
   
my_label . textAlignment = NSTextAlignmentCenter ;
    [
self . view addSubview : my_label ];
   
    [
self addBtnTitle : @" 开辟分线程 " frame : CGRectMake ( 10 , 200 , 200 , 35 ) Tag : 111 ];

}


- (
void )myBtnClick:( UIButton *)Btn{
   
   
NSDictionary *params = @{ @"key1" : @"value1" ,
                            
@"key2" : @"value2" } ;
   
// 开辟分线程
    [
NSThread detachNewThreadSelector : @selector (newThread:) toTarget : self withObject :params];
}


// 分线程
-(
void )newThread:( NSMutableDictionary *)dic
{
   
// 创建线程
   
// 判断 BOOL
   
NSThread *thread = [ NSThread currentThread ];
   
BOOL isMainThread = [thread isMainThread ];
   
   
NSLog ( @"---> thread = %d" ,isMainThread);
   
NSLog ( @"---> dic = %@ \n " ,dic);

   
// 创建 主线程
   
// 去网络请求获取数据 请求完成 必须要回到主线程刷新数据
    [
self performSelectorOnMainThread : @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

你可能感兴趣的:(iOS)