iOS: _block keyword

I have seen this sample code on "How To Use Blocks in iOS 5 Tutorial – Part 2". To take not of myself, I want to use their block of code that uses the _block keyword.


- (float)totalOrder {
 // 1 - Define and initialize the total variable
    __block float total = 0.0;
 // 2 - Block for calculating total
    float (^itemTotal)(float,int) = ^float(float price, int quantity) {
        return price * quantity;
    };
 // 3 - Enumerate order items to get total
    [self.orderItems enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        IODItem* item = (IODItem*)key;
        NSNumber* quantity = (NSNumber*)obj;
        int intQuantity = [quantity intValue];
        total += itemTotal(item.price, intQuantity);
    }];
 // 4 - Return total
    return total;
}


From the site I have linked or referenced above, going step-by-step, their explanation on using _block keyword 

  • We define and initialize the variable that will accumulate the total. Note the __block keyword. We will be using this variable inside of a Block. If we do not use the __block keyword, the Block we create below would create a const copy of this variable and use that when referenced inside the Block, meaning we would not be able to change the value inside of the Block. By adding this keyword we are able to be read from AND write to the variable inside of the Block.
  • Then, we define a Block variable and assign it a Block that simply takes a price and a quantity and returns the item total based on price and quantity.
  • This code segment goes over every object in the orderItems dictionary using a Block method, enumerateKeysAndObjectsUsingBlock: and uses the previous Block variable to find the total for each item for the quantity ordered and then adds that to the grand total (which is why we needed the __block keyword on the total variable since it is being modified inside of a Block).
  • Once we are done calculating the total for all the items, we simply return the calculated total.

Comments

Popular posts from this blog

Converting sectors into MB - Useful in understanding the sectors in iostat in Linux

What is Disk Contention?

Installing MySQL from source: Could NOT find Curses (missing: CURSES_LIBRARY CURSES_INCLUDE_PATH)