Objective C向创建者发送消息

时间:2012-01-26 11:30:50

标签: objective-c

我不太明白如何处理下一类任务:

@implementation SomeInterface

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

问题是 - 在doJob完成后,mo如何将消息发送回SomeInterface? 我应该使用NSNotificationCenter吗?

2 个答案:

答案 0 :(得分: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做了一些最终异步的事情(或者你只是等到方法返回);在这种情况下,您可能希望使用结果为dispatch_async的GCD' dispatch_get_main_queue来确保完成处理程序在主线程上发生。

Joachim Bengtsson撰写了a good introductory guide to blocks。至于他们如何与Grand Central Dispatch(以及如何一般使用GCD)进行互动,Apple's documentation是好的。

答案 1 :(得分:0)

是的,您可以使用NSNotificationCenter或编写回调方法