How do I post a NSNotification when using Grand Central Dispatch?

三世轮回 提交于 2019-11-30 23:43:44
Michael Dautermann

A couple possibilities here.

1)

How about [NSObject performSelectorOnMainThread: ...] ?

E.G.

-(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];
            }
        });
    });
}

More details at http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:

or 2)

Completion Callbacks

as seen at How can I be notified when a dispatch_async task is complete?

-(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];
            }
        });
    });
}

That is already correct. However why do you need to use notification if you already dispatch_get_main_queue()?

Just use

        dispatch_async(dispatch_get_main_queue(), ^{
            if (jpgData) {        
            //Do whatever you want with the image here
            }
        });

Anyway your original solution is fine. It's not blocking. Basically it'll save the file at other thread and once it's done it'll do what it takes.

What ever you do will be done on the same thread with the thread that call [[NSNotificationCenter defaultCenter] postNotificationName:kImageSavedSuccessfully object:self]; namely main thread.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!