The essence is this: there is a basket of goods that is stored on the server. Upon request, I get json as an NSArray, in which the elements are an NSDictionary, each of which, in turn, contains the product parameters like ID, image, amount, etc. I need to update the counter in the side menu of the mobile application (MP) in accordance with the number of products added (the sum of the amount parameters for all products). The whole mechanism of updating the counter in the MP has already been implemented, you just need to return the quantity in the method.

- (NSInteger)countOfProductsInCart { __block NSInteger itemsInCart = 0; [[OCRESTAPIClient sharedClient] fetchCartWithCompletion:^(NSArray *objects) { for (NSDictionary *item in objects) { itemsInCart += [[item objectForKey:@"amount"] integerValue]; } }]; return itemsInCart; } 

The problem is that first the program code passes, and only then all the actions in the block. Accordingly, return always returns 0 and only then the counter is updated. How do I return the already counted itemsInCart value in the method?

  • Thank! Understood how to do it. I did not even think that you can use the same blocks. - Schmopsel
  • Please publish the solution found as an answer. - Nicolas Chabanovsky

1 answer 1

Decision:

 - (void)countProductsInCart:(void(^)(NSInteger))completion { [[OCRESTAPIClient sharedClient] fetchCartWithCompletion:^(NSArray *objects) { NSInteger itemsInCart = 0; for (NSDictionary *item in objects) { itemsInCart += [[item objectForKey:@"amount"] integerValue]; } completion(itemsInCart); }]; }