SpaceDog SpaceDog - 1 year ago 45
Objective-C Question

Relplacing a block inside a block

I have created a class that is defined like this:

HEADER

typedef void (^myBlock)(NSString *value);

- (instancetype)initWithIdentifier:(NSString *)identifier
runOnSelection:(myBlock)runOnSelection;


When I init an object of this kind I do:

MyObject *object = [[MyObject alloc] initWithIdentifier:@"my id"
runOnSelection:^(NSString *value){
doThis();
doStuff();
doSomethingElse();
}];


The problem is that I have a lot of objects in sequence being initialized like this and all do the same thing.

I was thinking on creating a block for
doThis
,
doStuff
and
doSomethingElse
, like this:

void (^doALot)(NSString *value) = ^void(NSString *value) {
doThis();
doStuff();
doSomethingElse();
};


and replace the initializations with something like

MyObject *object = [[MyObject alloc] initWithIdentifier:@"my id"
runOnSelection:doALot()];


but the problem is that
doALot
require a parameter. How do I attach a block to something like that?

I know I can do

MyObject *object = [[MyObject alloc] initWithIdentifier:@"my id"
runOnSelection:^(NSString *value){
doALot(value)
}];


But I am wondering if I can do this without having to put it inside the block, by simply connecting the two. If I am not wrong, I have seen Apple doing this when they have APIs that have handlers, you can define the handler outside or inside, so I suspect this is possible.

How?

Answer Source

Create new block object like below-

typedef void (^myBlock)(NSString *value);

myBlock block=^(NSString *value){
    doThis();
    doStuff();
    doSomethingElse();
};

and replace the initialisations with something like

MyObject *object = [[MyObject alloc] initWithIdentifier:@"my id"
         runOnSelection:block];

Hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download