search

Home  >  Q&A  >  body text

ios - How to determine when an asynchronous operation (loop) has completely ended?

Requirement: After obtaining the album information, get the first picture and assign a value to self.editImageView for display.
Problem: But now I want to getImageForCollectionViewafter it is completely completed. ##self.editImageView assignment, then the question is, how can I judge that the getImageForCollectionView function has been completed?

 - (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) {
       
    }];
}
曾经蜡笔没有小新曾经蜡笔没有小新2744 days ago832

reply all(1)I'll reply

  • 黄舟

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

    Place time-consuming operations in non-main threads, and those that require UI updates in the main thread.

    __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);
    }];

    reply
    0
  • Cancelreply