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)
发布此通知以获取我想要的功能的正确机制是什么?
这里有几种可能性.
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)
或2)
完成回调
截至看到怎么能当dispatch_async任务完成后通知我?
| 归档时间: |
|
| 查看次数: |
5580 次 |
| 最近记录: |