gpt4 book ai didi

objective-c - GCD 等待队列中的所有任务完成

转载 作者:行者123 更新时间:2023-12-03 17:49:42 26 4
gpt4 key购买 nike

在我的应用程序中,我有照片上传功能,我希望我的主队列等到照片上传完成。这是我的代码:

    dispatch_group_t groupe = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.freesale.chlebta.photoUplaod", 0);

dispatch_group_async(groupe, queue, ^{

//Upload photo in same array with annonce
//++++++++++++++++++++++++++++++++++++++
if(!_annonce)
[KVNProgress updateStatus:@"جاري رفع الصور"];

__block NSInteger numberPhotoToUpload = _photoArray.count - 1;

for (int i = 1; i < _photoArray.count; i++) {
//check if image is asset then upload it else just decrement the photo numver because it's already uploaded
if ( [[_photoArray objectAtIndex:i] isKindOfClass:[ALAsset class]]){
ALAsset *asset = [_photoArray objectAtIndex:i];

NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]], 0.6);

PFFile *imageFile = [PFFile fileWithName:@"image.png" data:imageData];
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded)
[annonce addUniqueObject:imageFile forKey:@"photo"];
else
NSLog(@"Error image upload \n image :%i \n error: %@",i, error);

numberPhotoToUpload --;
}];
} else
numberPhotoToUpload --;

}

});

//Wait until Photo Upload Finished

dispatch_group_wait(groupe, DISPATCH_TIME_FOREVER);

// Some other Operation

但这不起作用,我的程序继续执行而不等待照片上传完成。

最佳答案

因为您在 block 中使用 saveInBackgroundWithBlock: 方法,对吗?

https://parse.com/docs/osx/api/Classes/PFFile.html#//api/name/saveInBackgroundWithBlock :

Saves the file asynchronously and executes the given block.

如果你确实想等待后台处理的 block ,则需要调用该方法的dispatch_group_enterdispatch_group_leave,如下所示。

dispatch_group_enter(groupe);
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
dispatch_group_leave(groupe);

...

}];

顺便说一下,

I want my main queue wait until photo upload is done

这不是一个好主意。不要阻塞主线程(主队列)。

App Programming Guide for iOS - Performance Tips - Move Work off the Main Thread

Be sure to limit the type of work you do on the main thread of your app. The main thread is where your app handles touch events and other user input. To ensure that your app is always responsive to the user, you should never use the main thread to perform long-running or potentially unbounded tasks, such as tasks that access the network.

关于objective-c - GCD 等待队列中的所有任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31290132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com