Storing a block in a collection

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


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

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.

Need Your Help

Is there a clean way to declare a Java array with the same value for each element?

java arrays

This isn't terribly important, but I was curious if there was a way to write a Java one liner possibly using guava or something to populate an array with elements that all have the same value. So ...

Accessing a Dictionary.Keys Key through a numeric index

c# .net dictionary

I'm using a Dictionary<string, int> where the int is a count of the key.