ios - 如何判斷一個非同步操作(循環)完全結束了呢?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-16 13:19:19
0
1
858

需求: 取得相簿資訊後取得第一張圖片並為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) {
       
    }];
}
曾经蜡笔没有小新
曾经蜡笔没有小新

全部回覆(1)
黄舟

將耗時的操作放在非主執行緒中,需要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);
}];
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板