使用Grand Central Dispatch时如何发布NSNotification?

Ric*_*Ric 3 objective-c nsnotifications grand-central-dispatch ios4

我发现,正如我在编写图像到文件时预测的那样,我的UI被封锁了一段时间,这是不可接受的.当我将图像写入文件时,然后发布NS通知,以便我可以执行与该完成相关的一些其他特定作业.原始工作但UI阻止代码:

-(void)saveImageToFile {
    NSString *imagePath = [self photoFilePath];
    BOOL jpgData = [UIImageJPEGRepresentation([[self captureManager] stillImage], 0.5) writeToFile:imagePath atomically:YES];

if (jpgData) {        
    [[NSNotificationCenter defaultCenter] postNotificationName:kImageSavedSuccessfully object:self];
}
Run Code Online (Sandbox Code Playgroud)

为了避免UI阻塞,我将writeToFile:放入Grand Central Dispatch队列,以便它作为并发线程运行.但是当写完成并且线程完成后,我想发布一个NSNotification.我不能在这里显示代码,因为它在后台线程中.但这是我想要完成的功能,意识到这不是可行的代码:

-(void)saveImageToFile {
    NSString *imagePath = [self photoFilePath];

    // execute save to disk as a background thread
    dispatch_queue_t myQueue = dispatch_queue_create("com.wilddogapps.myqueue", 0);
    dispatch_async(myQueue, ^{
        BOOL jpgData = [UIImageJPEGRepresentation([[self captureManager] stillImage], 0.5) writeToFile:imagePath atomically:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (jpgData) {        
            [[NSNotificationCenter defaultCenter] postNotificationName:kImageSavedSuccessfully object:self];
            }
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

发布此通知以获取我想要的功能的正确机制是什么?

Mic*_*ann 6

这里有几种可能性.

1)

[NSObject performSelectorOnMainThread:...]怎么样?

例如

-(void) doNotification: (id) thingToPassAlong
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kImageSavedSuccessfully object:thingToPassAlong];
}

-(void)saveImageToFile {
    NSString *imagePath = [self photoFilePath];

    // execute save to disk as a background thread
    dispatch_queue_t myQueue = dispatch_queue_create("com.wilddogapps.myqueue", 0);
    dispatch_async(myQueue, ^{
        BOOL jpgData = [UIImageJPEGRepresentation([[self captureManager] stillImage], 0.5) writeToFile:imagePath atomically:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (jpgData) {   
                [self performSelectorOnMainThread: @selector(doNotification:) withObject: self waitUntilDone: YES];
            }
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

更多详细信息,请访问http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:

或2)

完成回调

截至看到怎么能当dispatch_async任务完成后通知我?

  • 你对performSelectorOnMainThread的调用是多余的.dispatch_async(dispatch_get_main_queue(),...已经把你放在主线程上.重要的部分是postNotificationName:object:是我正在寻找的东西,所以很好的节目.谢谢:) (2认同)