## Using Blocks (i.e. Closures) To Improve Transactional Code

on November 21st, 2010 by Tom 4 Comments Cocoa

This article will be about using blocks to improve transactional code. When I say "transactional" code, I mean code that has an opening, a middle, and a closing, where the opening and the closing have to be matched. You see it in a few places in Cocoa, such as:

• KVO:
1. willChangeValueForKey:
2. change the value
3. didChangeValueForKey:
• NSGraphicsContext:
1. saveGraphicsState
2. do some drawing
3. resoreGraphicsState
• NSFileWrapper:
1. open a file
I’m going to show you a "before and after" comparison of a function that uses NSGraphicsContext and NSAffineTransformation.