365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Mar 17

Day 19: +mainQueue & Blocks

Today I’ll take a little break from the drawing series. Yesterday I went to NSCoderNight in London (thanks to @abizern for starting this) and had a little chat with @mikeabdullah about blocks. I mentioned one snippet of code I use quite a lot and I thought it’d be nice to mention it here. It involves blocks again which makes in 10.6-only.

It often happens that I want to delay some action to the next run loop. The usual way to do this is with performSelector:withObject:afterDelay: but this forces you to create an extra method and pass it all the extra arguments you need (maybe as a dictionary) to this other function. Blocks would be perfect to replace this.

As of 10.6, NSOperationQueue has a +mainQueue which is serialized (one operation at a time) and runs on the main thread. We can send blocks to this queue with -addOperationWithBlock: which basically has the same effect as the old method.


  1. 365cocoa posted this