搜索

首页  >  问答  >  正文

ios - 如何判断一个异步操作(循环)完全结束了呢?

需求 : 获取相册信息后获取第一张图片并为self.editImageView赋值显示.
问题 : 但是我现在想在getImageForCollectionView完全结束后来为self.editImageView赋值,那么问题来了,我如何才能判断getImageForCollectionView函数已经进行完毕?

 - (void)getImageForCollectionView{
    _library = [[ALAssetsLibrary alloc] init];
    self.photos = [NSMutableDictionary dictionary];
    [_library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group) {
            NSMutableArray *array = [NSMutableArray array];
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if (result) {
                    [array addObject:result];
                }
            }];
            [self.photos setValue:array forKey:[group valueForProperty:@"ALAssetsGroupPropertyName"]];
        }
    } failureBlock:^(NSError *error) {
       
    }];
}
曾经蜡笔没有小新曾经蜡笔没有小新2816 天前878

全部回复(1)我来回复

  • 黄舟

    黄舟2017-05-16 13:21:19

    将耗时的操作放在非主线程中,需要UI更新的放在主线程中。

    __weak typeof(self) weakSelf = self;
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // not in main block task
        [weakSelf getImageForCollectionView];
        dispatch_async(dispatch_get_main_queue(), ^{
            // main block. change ui
            NSLog(@"%@", weakSelf.photos);
        });
    });

    EDIT:

    - (void)getImageForCollectionView:(void(^)(void))callback {
        _library = [[ALAssetsLibrary alloc] init];
        self.photos = [NSMutableDictionary dictionary];
        
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [_library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                if (group) {
                    NSMutableArray *array = [NSMutableArray array];
                    [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                        if (result) {
                            [array addObject:result];
                        }
                    }];
                    [self.photos setValue:array forKey:[group valueForProperty:@"ALAssetsGroupPropertyName"]];
                }
            } failureBlock:^(NSError *error) {
                
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback();
            });
        });
    }
    [self getImageForCollectionView:^{
        // ...
        NSLog(@"%@", self.photos);
    }];

    回复
    0
  • 取消回复