Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a block in a collection

Is it possible to directly store a block in a collection such as NSArray?

like image 897
Nick Moore Avatar asked Mar 09 '11 17:03

Nick Moore


2 Answers

Yes, blocks are valid Objective-C objects, following all the conventions of NSObject. Just do the copy/autorelease dance:

[array addObject:[[block copy] autorelease]];

For ARC - omit the copy and autorelease calls:

[array addObject:block];
like image 50
Eimantas Avatar answered Sep 29 '22 12:09

Eimantas


Can't figure out how to respond in the comment thread on Eimantas' answer, but -copy is necessary because the block may have been created on the stack. See 2) in bbum's post on the topic.

like image 38
numist Avatar answered Sep 29 '22 11:09

numist