Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a block object instead of a selector?

I have:

[self schedule:@selector(tickhealth)];

And tickHealth method only has one line of code:

-(void)tickHealth
{
    [hm decreaseBars:0.5];
}

is it possible to use block objects in place of a selector. for example something like:

[self schedule:^{
    [hm decreaseBars:0.5];
}];
like image 227
ninjaneer Avatar asked Feb 03 '23 16:02

ninjaneer


1 Answers

As Caleb & bbum correctly pointed out you cannot simply pass a block to your existing (and unchanged) - (void)schedule:(SEL)selector; method.

You can however do this:

Define block type:

typedef void(^ScheduleBlock)();

Change schedule: method to be defined similar to this:

- (void)schedule:(ScheduleBlock)block {
    //blocks get created on the stack, thus we need to declare ownership explicitly:
    ScheduleBlock myBlock = [[block copy] autorelease];
    //...
    myBlock();
}

Then call it like this:

[self schedule:^{
    [hm decreaseBars:0.5];
}];

Further Objective-C block goodness compiled by Mike Ash that will get you kickstarted with blocks:

  • http://mikeash.com/pyblog/friday-qa-2008-12-26.html
  • http://mikeash.com/pyblog//friday-qa-2009-08-14-practical-blocks.html
  • http://mikeash.com/pyblog/friday-qa-2011-06-03-objective-c-blocks-vs-c0x-lambdas-fight.html
like image 110
Regexident Avatar answered Feb 09 '23 00:02

Regexident