S.J
S.J

Reputation: 3071

Need assistance understanding part of blocks

I was reading the Ray Wenderlich in-app purchases tutorial, and I just want to understand the block part of it.

  1. _completionHandler = [completionHandler copy]; why copy is used to assign block to this variable?
  2. This block:

    [[RageIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) {
        if (success) {
            _products = products;
            [self.tableView reloadData];
        }
        [self.refreshControl endRefreshing];
    }];
    

    is passed as a parameter to method, but the method is present in another class. How another class will reference this class tableview and refreshControl ?

Upvotes: 0

Views: 62

Answers (1)

Joel
Joel

Reputation: 16124

  1. Blocks exist on the stack. In order to keep a block around after it goes out of scope you need to copy it to move it to the heap. You can then treat it like any other object and use it later. In that example they are copying the block to an ivar so it can be used in another method.

  2. When you pass a block as a parameter it encapsulates all variables from its local scope and can access them after they go out of scope. See the documentation here.

Upvotes: 2

Related Questions