iphone - 从其他 NSThread 委托(delegate)回调

标签 iphone objective-c xcode nsthread

我有一个带有 .delegate 属性的对象,我在方法“doJob”中操作它。我将此属性分配为“self”,并且当该对象完成其工作时将调用我的函数。到目前为止一切都很好。

现在我想在单独的线程中操作这个对象。

我正在使用 [NSThread detachNewThreadSelector...] 来运行“doJob”函数。 在这种情况下,我的委托(delegate)方法没有被调用。我想这是因为“self”指向新线程而不是主线程。好的。我在创建线程时将 self 作为参数传递给函数,但它仍然不起作用。我想念什么?

我当前的代码如下:

- (void)mainFunction
{
    [NSThread detachNewThreadSelector:@selector(doJob:) toTarget:self witObject:self];
}

- (void)doJob:(MyObject*)parentThread
{
    ManipulatedObject *obj = [[ManipulatedObject alloc] init];
    obj.delegate = parentThread;
    [object startJob];
}

最佳答案

GCD 将使您的大部分多线程问题变得微不足道。你可以这样做:

- (void)mainFunction
{
    // Runs your task on a background thread with default priority.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        ManipulatedObject * obj = [[ManipulatedObject alloc] init];

        [obj startJob];  // I'm assuming this is sychronous.

        // The callback is explicitly run on the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{

            // Your callback here.

            [obj release];
        });
    });
}

这就是您所要做的,就这么简单。所有相关代码都是内联的并且在一起。

如果您希望 ManipulatedObject 显式调用该 block ,那么您可以将该功能添加到 ManipulatedObject。为此,您应该:

  1. 为了方便起见定义 block 类型typedef void(^MyCallback)();

  2. 添加@property(非原子,复制)MyCallback block ;@synthesize block 。不要忘记副本。

  3. 当您需要dispatch_async(dispatch_get_main_queue(), [self block]);时调用该 block 。

如果您的委托(delegate)需要进行不止一种回调,那么您将需要为每个回调分配一个 block 。虽然这是一个小小的不便,但为了您获得的所有便利,这是值得的。

有关 block 和 GCD 的更全面说明,请查看 WWDC 2011 session 308。

关于iphone - 从其他 NSThread 委托(delegate)回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6993924/

相关文章:

iPhone模拟器屏幕旋转

swift - 错误域=NSURLErrorDomain 代码=-999 "cancelled"Xcode

xcode - 当我尝试存档项目时 - 位码错误

iphone - 如果我们有效地选择 UITableViewCellStyleValue1,如何设置 cell.textLabel 和 cell.detailTextLAbel?

iphone - 使用selector方法调用C Function并在iPhone的c方法中访问self

objective-c - 如何从 IBAction 方法获取事件

objective-c - Cocoa 中的 OCR(从照片中读取文本)?

iphone - 如何检测进入 UIButton 框架的触摸?

objective-c - 无法启动 iOS 模拟器; launchd 没有响应

iphone - UIWebView 中的谷歌地图从核心传递数据