我正在搞一個爛攤子,並試圖找出一個熟練的方式來處理這個問題,但我陷入困境。我現在的問題是,在我希望它們成爲代碼之前,我已經執行了代碼,它必須處理我的代碼塊。塊內的塊不知道該怎麼辦
下面的代碼的問題在於postToForm
方法正在被調用並在我的convertedImages
被添加到之前執行。我該如何解決這個問題,以便它等待發生?或者我是以這種錯誤的方式去做的? (我需要知道的內存使用太多,需要釋放內存後作出後)。
這裏是我的代碼包含問題:
// create serial queue
dispatch_queue_t queue = dispatch_queue_create("myQueue", 0);
// create dispatch group
dispatch_group_t group = dispatch_group_create();
for(id photos in photoUrls) {
NSString *urlString = photos;
// enqueue operation in queue
dispatch_async(queue, ^{
// enter the group
dispatch_group_enter(group);
// do something async, I do use another dispatch_queue for example
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// wrap in autoreleasepool to release memory upon completion
@autoreleasepool {
// here for example the nested operation sleeps for two seconds
NSURL *url = [NSURL URLWithString:urlString];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:url resultBlock:^(ALAsset *asset) {
//TODO: Deal with JPG or PNG
NSData *imageData = UIImageJPEGRepresentation([self thumbnailForAsset:asset maxPixelSize:1000], 0);
NSString *base64 = [imageData base64EncodedString];
NSLog(@"base64::%@",base64);
[convertedImages addObject:base64];
} failureBlock:^(NSError *error) {
NSLog(@"that didn't work %@", error);
}];
dispatch_group_leave(group);
}
});
// wait until the nested async operation leaves the group (e.g finishes its job)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"Finished single operation.");
});
}
// will be called once all operations complete
dispatch_async(queue, ^{
NSLog(@"Finished all jobs. ");
NSLog(@"how many::%lu",(unsigned long)convertedImages.count);
[jsonWithPhotos setObject:convertedImages forKey:@"photo64"];
[self postToForm];
});
哦,我花了這麼多時間在這個簡單的答案!小心解釋爲什麼它能正確工作? – BluGeni