-3

My question is really straight forward. When returning a block from a method or function or block itself how do you pass that returning block from such into a variable that is receiving that returned block?

  • 1
    Are you looking for how to return a block from a method? – Abhinav Sep 26 '15 at 01:53
  • This thread has good explanation http://stackoverflow.com/questions/13193673/how-do-i-create-an-objective-c-method-that-return-a-block – Abhinav Sep 26 '15 at 01:59
  • @Abhinav No, i was looking for how to receive a returning block from a method or function or block it self. How would you receive a block being returned? But i understand where the confusion lies. – Humzaa Choudryy Sep 26 '15 at 03:55

3 Answers3

1

My question is really straight forward. When returning a block from a method or function or block itself how do you pass that returning block from such into a variable that is receiving that returned block?

How do you "pass that returning" value for any type of value?

Assignment.

There is nothing special about returning a block, it is just a value - in this case a pointer value to a block object - and it is returned and assigned to a variable just like any other value. If the return value is of, say, double type store it in a variable of the same type; if the returned value is some block type then you store it in a variable with the same block type.

As with any type with a moderately complex type declaration you'll probably find it easier to first use typedef to give it a nice short name. E.g.:

typedef int (^SomeIntFunction)(int, int)

SomeIntFunction selectFunction() { ... }

SomeIntFunction sif = selectFunction();

int result = sif(42, 24);

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86
0

Here is one way:

typedef void(^blockTakingInt)(int);

// Returns a block
blockTakingInt f()
{
    return ^(int i) {
        printf("i = %d\n", i);
    };
}

// Accepts a block as a parameter
void g(int i, blockTakingInt b)
{
    b(i);
}

// Store the block returned by the function f in b, and pass it to g
void (^b)(int) = f();
g(4, b);
sbooth
  • 16,646
  • 2
  • 55
  • 81
0

First of all declare your block syntax.

write below syntax at the bottom of #import ....

typedef void(^completionBlock) (NSString *message);

Now create function with block:

- (void)callFunctionWithBlock: (NSString *)text completion: (completionBlock)callBlock {
    NSLog(@"%@", text);

    callBlock([NSString stringWithFormat:@"block with return message: %@", text]);
}

Call your function:

[self callFunctionWithBlock:@"testing block" completion:^(NSString *message) {
            NSLog(@"%@", message);
}];
Mehul Sojitra
  • 1,181
  • 9
  • 15
  • i was looking for how to receive a returning block from a method or function or block it self. How would you receive a block being returned? But i understand where the confusion lies. – Humzaa Choudryy Sep 26 '15 at 04:49