Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an Obj-C Block execute itself?

Tags:

People also ask

How do blocks work in Objective-C?

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary .


This is an extension of this queston: Is it possible to create a category of the "Block" object in Objective-C.

Basically while it seems possible to create a category on blocks, either through NSObject or NSBlock, I'm having trouble understanding how the block would be able to evaluate itself. The example given in the answer to the last question:

- (void) doFoo {
  //do something awesome with self, a block
  //however, you can't do "self()".  
  //You'll have to cast it to a block-type variable and use that
}

Implies that it is possible to somehow cast self to a block variable, but how would one execute the block itself? For example, say I did a category on NSBlock and in a method did:

NSBlock* selfAsBlock = (NSBlock*)self;

Is there any message I can send to selfAsBlock to have the block evaluate?