ios store ^block in dictionary or array?

ios, iphone, objective-c, objective-c-blocks

Solution

You can store object into collection. But take care of the scope: Copy them when they will be kept out of a function scope. This is your case since you are storing them in a array.

[NSArray arrayWithObject: 
[[^{ NSLog(@"block 1"); } copy] autorelease],
[[^{ NSLog(@"block 2"); } copy] autorelease], nil]

On ARC, you still need to tell it you absolutely needs to copy your block. It should release the block when the array is freed.

  [NSArray arrayWithObject: 
    [^{ NSLog(@"block 1"); } copy],
    [^{ NSLog(@"block 2"); } copy], nil]

Problem

Can I store ^block in a dictionary or an array? I need to listen to a server notification which I need to provide a block to handle the notification, and in my project several view controllers all want to hear the notification, so I made a generic notification manager, which has its own block for handling server notification and it has an array of delegates, so in the manager's block: ``` - (^)(NSString *message){ for (delegate in allDelegates) { delegate.handlerBlock(message); } } ``` but can I store blocks in a collection?

Original source