Can i safely post messages containing code blocks within my program address space? Tests works but is this legal?
typedef void (^EmitBlock)(NSDictionary* args);
- (void) subscribe {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(on_emit:) name:kEmit object:nil];
}
- (void) on_emit:(NSNotification*) notification
{
EmitBlock completion = [[notification userInfo] valueForKey:@"completion"];
completion(@{@"result" : @"Ok"});
}
- (void) post:(EmitBlock) completion {
[[NSNotificationCenter defaultCenter] postNotificationName:kEmit
object:nil userInfo:@{@"completion":
^(NSDictionay* args) { NSLog(@"%@", args); }
}];
}
Blocks are Objective-C objects, so you can put them into an dictionary and use them in the userinfo of a notification.
But note that according to the Transitioning to ARC Release Notes:
… You still need to use
[^{} copy]when passing “down” the stack intoarrayWithObjects:and other methods that do a retain.
you should put a copy of the block into the dictionary:
[[NSNotificationCenter defaultCenter] postNotificationName:@"kEmit"
object:nil
userInfo:@{
@"completion" : [^(NSDictionary* args) { NSLog(@"%@", args); } copy]
}
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With