码迷,mamicode.com
首页 > 编程语言 > 详细

通过GCD、NSOperationQueue队列、NSThread三种方法来创建多线程

时间:2015-03-29 17:56:08      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *remindLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)sendBtnClick:(UIButton *)sender {

    /*--第一种采用GCD发送请求并刷新UI--*/
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        sleep(2);
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            _remindLabel.text=@"发送成功";
        });
       
    });
     /*--第二种采用NSBlockOperation、NSOperationQueue队列发送请求并刷新UI--*/
     NSOperationQueue *myQueue=[[NSOperationQueue alloc]init];
     NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{
       //延时2秒
        sleep(2);
        //主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            
             _remindLabel.text=@"发送成功";
        });
    }];
    [myQueue addOperation:operation];
    
    
    /*--第三种采用NSThread发送请求并刷新UI--*/
    [NSThread detachNewThreadSelector:@selector(sendState) toTarget:self withObject:nil];
    
    
}
-(void)sendState
{
    sleep(2);
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self updateLabel];
    });
}
-(void)updateLabel
{
   _remindLabel.text=@"发送成功";
}
@end

技术分享

通过GCD、NSOperationQueue队列、NSThread三种方法来创建多线程

标签:

原文地址:http://www.cnblogs.com/thbbsky/p/4375961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!