iOS 4 Blocks
So … through a weird series of events, I ended up working on an iPad app at work that someone even mentioned in a video. I didn’t write the original app, but I have become responsible for it, which was all fine and dandy until it just started crashing all the time.
Fortunately, I found out what the problem was. And the solution turned out to be to use “blocks”, which became available in iOS 4. What are blocks? Essentially, they’re ways to encapsulate bits of your code to execute later.
Here’s a very simple example:
for (int i = 0; i < 100; i++) { NSString *countString = [NSString stringWithFormat:@"Now we are at %d", i]; countLabel.text = countString; }
You might think that this would update a UILabel somewhere, animating it from 0 to 99. But it won't because the app doesn't have a chance to display until this code is completely finished. So what you can do instead is to use a block like this:
for (int i = 0; i < 100; i++) { [[NSOperationQueue mainQueue] addOperationWithBlock: ^{ NSString *countString = [NSString stringWithFormat:@"Now we are at %d", i]; countLabel.text = countString; }]; }
What this does is it takes those two lines of code and executes them later in 100 separate chunks so that the UILabel has a chance to update. The most amazing thing about blocks is that they encapsulate not just the code, but the state of all the variables leading into the code. This is extremely useful if you want to, say, decompress a bunch of files on startup.