2012-01-26 64 views
0

我不太明白如何應對接下來的任務類型:目標C發送消息給創作者

@implementation SomeInterface 

-(void)DoSomething 
{ 
    MyObj * mo = [MyObj new]; 
    [mo doJob]; 
} 
end 

的問題是 - 如何doJob後莫發送消息回SomeInterface完了? 我應該使用NSNotificationCenter嗎?

回答

2

隨着iOS 4的,可能是最容易做的事情是塊傳遞給doJob是決定它應該完成時做的。因此,舉例來說...

MyObj.h:

// create a typedef for our type of completion handler, to make 
// syntax cleaner elsewhere 
typedef void (^MyObjDoJobCompletionHandler)(void); 

@interface MyObj 

- (void)doJobWithCompletionHandler:(MyObjDoJobCompletionHandler)completionHandler; 

@end 

MyObj.m:

- (void)doJobWithCompletionHandler:(MyObjDoJobCompletionHandler)completionHandler 
{ 
    /* do job here ... */ 

    // we're done, so give the completion handler a shout. 
    // We call it exactly like a C function: 
    completionHandler(); 

    /* alternatives would have been to let GCD dispatch it, 
    but that would lead to discussion of GCD and a bunch of 
    thread safety issues that aren't really relevant */ 
} 

在SomeInterface.m:

-(void)DoSomething 
{ 
    MyObj * mo = [MyObj new]; 
    [mo doJobWithCompletionHandler: 
     ^() // you can omit the brackets if there are no parameters, but 
      // that's a special case and I don't want to complicate things... 
     { 
      NSLog(@"whoop whoop, job was done"); 

      // do a bunch more stuff here 
     } 
    ]; 
} 

我假設在現實中你正在做的事情最終會在DoJob中異步(否則你只能等到該方法返回)。在這種情況下,您可能希望使用GCD的dispatch_async,結果爲dispatch_get_main_queue以確保完成處理程序發生在主線程上。

約阿希姆本特鬆寫了a good introductory guide to blocks。至於他們如何與Grand Central Dispatch進行互動(以及如何使用GCD),Apple's documentation是很好的。

+0

謝謝tommy! – Nils

+1

現在你讓我非常明顯地知道我只是使用了我的名字: P但是如果你有一個代表工作的對象,那麼NSOperationQueue可能比GCD更適合。 – nevyn

0

是的,你可以使用NSNotificationCenter或寫回調方法

+2

通知,委派模式或回調塊,請選擇。 – mit3z

+0

我已經用NSNotificationCenter做了這個,但是我認爲這裏的回調比較好,而且我不明白怎麼做回調( – Nils