objective-c – 如何在使用Grand Central Dispatch时发布NSNotif
我发现,正如我在编写图像到文件时预测的那样,我的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]; } 为了避免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]; } }); }); } 发布此通知以获取我想要的功能的正确机制是什么? 解决方法
这里有几种可能性.
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",^{ if (jpgData) { [self performSelectorOnMainThread: @selector(doNotification:) withObject: self waitUntilDone: YES]; } }); }); } 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) 完成回调 见于How can I be notified when a dispatch_async task is complete? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |