天天看點

多線程之NSInvocationOperation

多線程程式設計是防止主線程堵塞,增加運作效率等等的最佳方法。而原始的多線程方法存在很多的毛病,包括線程鎖死等。在cocoa中,apple提供了nsoperation這個類,提供了一個優秀的多線程程式設計方法。

本次介紹nsoperation的子集,簡易方法的nsinvocationoperation:

@implementation mycustomclass

- (void)launchtaskwithdata:(id)data

{

//建立一個nsinvocationoperation對象,并初始化到方法

//在這裡,selector參數後的值是你想在另外一個線程中運作的方法(函數,method)

//在這裡,object後的值是想傳遞給前面方法的資料

nsinvocationoperation* theop = [[nsinvocationoperation alloc] initwithtarget:self

selector:@selector(mytaskmethod:) object:data];

// 下面将我們建立的操作“operation”加入到本地程式的共享隊列中(加入後方法就會立刻被執行)

// 更多的時候是由我們自己建立“操作”隊列

[[myappdelegate sharedoperationqueue] addoperation:theop];

}

// 這個是真正運作在另外一個線程的“方法”

- (void)mytaskmethod:(id)data

// perform the task.

@end

一個nsoperationqueue 操作隊列,就相當于一個線程管理器,而非一個線程。因為你可以設定這個線程管理器内可以并行運作的的線程數量等等。下面是建立并初始化一個操作隊列:

@interface  myviewcontroller : uiviewcontroller {

nsoperationqueue *operationqueue;

//在頭檔案中聲明該隊列

@implementation myviewcontroller

- (id)init

self = [super init];

if (self) {

operationqueue = [[nsoperationqueue alloc] init]; //初始化操作隊列

[operationqueue setmaxconcurrentoperationcount:1];

//在這裡限定了該隊列隻同時運作一個線程

//這個隊列已經可以使用了

return self;

- (void)dealloc

[operationqueue release];

//正如alan經常說的,我們是程式的好公民,需要釋放記憶體!

[super dealloc];

簡單介紹之後,其實可以發現這種方法是非常簡單的。很多的時候我們使用多線程僅僅是為了防止主線程堵塞,而nsinvocationoperation就是最簡單的多線程程式設計,在iphone程式設計中是經常被用到的。

繼續閱讀