Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Posting code blocks within userInfo using NSNotificationCenter?

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); }
    }];
}
like image 332
Vladimir Koltunov Avatar asked Jan 27 '26 13:01

Vladimir Koltunov


1 Answers

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 into arrayWithObjects: 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]
     }
 ];
like image 80
Martin R Avatar answered Jan 29 '26 03:01

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!