Nick Moore
Nick Moore

Reputation: 15857

Storing a block in a collection

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

Upvotes: 13

Views: 2712

Answers (2)

Eimantas
Eimantas

Reputation: 49354

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];

Upvotes: 23

numist
numist

Reputation: 627

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.

Upvotes: 1

Related Questions