Detect real end of the for () loop in objective-c

后端 未结 3 1241
不知归路
不知归路 2021-01-27 09:16

I\'m going to show in my app a sort of UIActivityIndicatorView while parsing several JSON objects, inside a for () loop. I can\'t figure WHERE I must place the [UIActivityIndica

3条回答
  •  -上瘾入骨i
    2021-01-27 09:28

    Solution is to

    1. Simplify the code so that is obvious what is being done there (declaring the blocks beforehand)

    2. Count how many requests are running and perform the global actions only when all the requests are completed.

    typedef void (^AFJSONSuccessBlock) (NSURLRequest *request, NSHTTPURLResponse *response, id JSON);
    typedef void (^AFJSONFailureBlock) (NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON);
    
    [UIActivityIndicatorView startAnimating];
    
    __block int numRequests = [arrayJSON count];
    
    AFJSONSuccessBlock onSuccess = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {   
        [...]
    
        numRequests--;
    
        if (numRequests == 0) {
            [UIActivityIndicatorView stopAnimating];
        }
    };
    
    AFJSONFailureBlock onFailure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        [...]
    
        numRequests--;
    
        if (numRequests == 0) {
            [UIActivityIndicatorView stopAnimating];
        }
    };
    
    for (NSString* jsonPath in arrayJSON) {
        NSString* absolutePath = [NSString stringWithFormat:@"http://WWW.REMOTESERVERWITHJSONSOURCE.NET/%@", jsonPath];
        NSURL *url = [NSURL URLWithString:absolutePath];
    
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        AFJSONRequestOperation *operation;
        operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                                    success:onSuccess
                                                                    failure:onFailure];
        [operation start];
    }
    

提交回复
热议问题