Ios多线程编程:NSOperation和NSOperationQueue

NSOperation是个抽象类,你可以自定义子类或者用系统定义好的(NSInvocationOperation 或 NSBlockOperation)类

如果你熟悉Java或一个它的变种语言,NSOperation就和java.lang.Runnable接口很相似。和Java的Runnable一样,NSOperation也是设计用来扩展的,并且最低仅需重写一个方法。对于NSOperation这个方法是-(void)main。一个使用NSOperation的最简单方法就是将其放入NSOperationQueue中。一旦一个操作被加入队列,该队列就会启动并开始处理它。一旦该操作完成队列就会释放它。

 

 NSInvocationOperation:

要职责就是调用某个对象的一个指定的方法。

-

- (void)viewDidLoad

{

    [superviewDidLoad];

 

    NSInvocationOperation *aOpt = [[NSInvocationOperation alloc]

                                   initWithTarget:self selector:@selector(doSomeThing) object:nil];

    NSOperationQueue *queue = [[NSOperationQueuealloc] init];

    

    [queue addOperation:aOpt];

    

    

    NSLog(@"mian thread");

}

- (void)doSomeThing

{

    //读取大量大延迟数据等等

    //可以使用performSelectorOnMainThread来将得来的数据返回到主线程

    NSLog(@"do something");

    for (int counter = 0; counter < 1000;counter++){

        NSLog(@"Count = %d",counter);

    }

}

 

NSBlockOperation:

- (void)viewDidLoad

{

    [superviewDidLoad];

 

    NSInvocationOperation *aOpt = [NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"Main Thread = %@", [NSThreadmainThread]);

        NSLog(@"Current Thread = %@", [NSThreadcurrentThread]);

        for (int counter = 0; counter < 1000;counter++){

            NSLog(@"Count = %d", counter);

        }

    }];

    NSOperationQueue *queue = [[NSOperationQueuealloc] init];

    

    [queue addOperation:aOpt];

    

    NSLog(@"mian thread");

}

 

 

 

 

 

 

posted @ 2013-04-26 17:18  shangdahao  阅读(2318)  评论(0编辑  收藏  举报