2012-03-02 60 views
0

我經常收到一些我需要在其他線程上處理的回調函數,我想將這些處理方法排列在一個線程上,以便它們按順序運行。我不想使用原始的NSThread(因爲工作太多),也不想使用GCD(因爲需要支持iOS 3.1)。開始查看NSOperation,但需要繼承,傳遞所需的數據等。然後開始考慮runLoops ......無論如何,實現這個任務的便捷方式是什麼?如何在其他線程上排列我的方法回調?

+0

線程從來不簡單。使用它們時,你總是需要做一些工作。 – v1Axvw 2012-03-02 15:32:23

回答

1

NSOperation比運行循環更容易設置。你不會說你的回調是什麼。它們是否起作用?選擇?塊?對象?

您的NSOperation子類只需要覆蓋main並提供一種將回調傳遞給操作的方法。

@interface MyOperation : NSOperation 
{ 
@private 
    CallbackType callback; // is e.g. a function pointer 
    void* context;   // a parameter for the callback as an example 
} 
-(id) initWithCallback: (CallbackType) newCallback; 
      andContext: (void*) newContext; 
@end 

@implementation MyOperation 

-(id) initWithCallback: (CallbackType) newCallback 
{ 
    self = [super init]; 
    if (self != nil) 
    { 
     callback = newCallback; 
     context = newContext; 
    } 
    return self; 
} 

-(void) main 
{ 
    callback(context); 
} 

@end 
+0

我正在使用套接字流,並且我正在調用 - (void)流:(NSStream *)theStream handleEvent:(NSStreamEvent)當從流中讀取數據時的streamEvent。我想將讀取流的處理放入隊列中。但我需要通過(有一個處理程序當前theStream,指向聲明的inputStream和outputStream,傳遞緩衝區(NSMutableData)。 – Centurion 2012-03-02 16:19:15