Friday, August 17, 2012

Objective-C blocks for fun

Today I had to solve a simple problem and since I am a lazy programmer I always tend to look for the solution that is the most easy to implement (less coding) but I never choose the easiest path to find this solution. I mean I try to follow this sentence: "Un objet est parfait quand on ne peut plus rien lui retirer de futile" which could more or less be translated to "An object is perfect when no more can be taken away". I don't know who ever said that but I often remind me this sentence when I work.

Problem:

I want to register a timer (NSTimer) that runs a block.


Solution:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7
      target:[NSBlockOperation blockOperationWithBlock:^{ /* do this! */ }]
      selector:@selector(main)
      userInfo:nil
      repeats:NO
];

The NSBlockOperation instance is retained by the timer.
The -[NSBlockOperation main] will run the block.

 Enjoy :)

3 comments:

  1. Nice! This must be my newest favorite iOS trick. Thanks!

    ReplyDelete
    Replies
    1. Thank you very much! Feedback is always welcomed. Feel free to browse the other articles as well.

      Delete
  2. Marcos Sánchez-DehesaOctober 4, 2012 at 5:21 PM

    I agree. This is a really neat line of code ;)

    ReplyDelete