IOS 多线程 NSOperation GCD

1.NSInvocationOperation 

 NSInvocationOperation * op;

 

 

    NSOperationQueue * que = [[NSOperationQueuealloc]init];

    op = [[ NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run:) object:@"aaa"];

    [que addOperation:op];

    //  这里不要使用   op start,否则就会出现住线程阻塞的现象。  默认情况下,调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作。只有将operation放到一个NSOperationQueue中,才会异步执行操作。

-(void)run:(id)data

{

    while (![op isCancelled])

    {

        [NSThreadsleepForTimeInterval:1];

        NSLog(@"run");

    }

}

通过   [op cancel];   来停止线程

 

2.

 __block NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^(){

        while ( ![op isCancelled])

        {

            [NSThread sleepForTimeInterval:0.3];

            

            NSLog(@"cccc");

        }

    }];

 

NSOperationQueue * que = [[NSOperationQueuealloc]init];

[que addOperation:op];

这里也需要通过  queue来控制,使用start的话也会造成阻塞。

这里的  op  需要使用 __block 来控制,因为在^(){}里面用到,否则不对。

 

3.自定义 NSOperation

 

#import <Foundation/Foundation.h>

@interface MyOperation : NSOperation

@end

 

#import "MyOperation.h"

 

@implementation MyOperation

 

-(void)main

{

    @autoreleasepool

    {

        while ( YES )

        {

            

            [NSThreadsleepForTimeInterval:0.3];

            

            if( [self isCancelled] )

                break;

            

            NSLog(@"aaaaaa");

        }

    }

}

 

//  如何调用

-(void)aaaa

{

    static BOOL bFlog = NO;

    if( !bFlog )

    {

        _op = [[MyOperation alloc]init];

        NSOperationQueue * que = [[NSOperationQueuealloc]init];

        

        [que addOperation:_op];

    }

    else

    {

        [_op cancel];

    }

    bFlog = YES;

}

 

3.  GCD

 dispatch_async(dispatch_get_global_queue(0, 0), ^(void){

        

        

        for( NSInteger index = 0; index < 10; ++ index )

        {

            [NSThreadsleepForTimeInterval:0.3];

            

            NSLog(@"index:%d",index);

            

            dispatch_async(dispatch_get_main_queue(), ^(void){

                

                _label.text = [NSString stringWithFormat:@"index:%d",index];

            });

        }

 

    });

posted on 2014-02-12 19:15  景树园  阅读(250)  评论(0编辑  收藏  举报

导航