0

I'm trying to figure out how to declare a method that takes a block as an argument and just logs an integer value from the outside scope. Most examples I see are doing this on some Apple API like indexesOfObjectsPassingTest: but I just want to create my own simple version. This is what I have, which is currently not working:

@interface IAViewController ()
+(void)tell2:(void(^)(void)) thisBlock;
@end

...

NSInteger someInt=289456;
[IAViewController tell2:^{
    NSLog(@"what is this? %i", someInt);
}];

// ? how do I make this method signature work
+(void) tell2:(void (^thisBlock)) myInt{
    thisBlock(myInt);
}

How can I make the method signature params work correctly to output 289456?

jscs
  • 63,694
  • 13
  • 151
  • 195
timpone
  • 19,235
  • 36
  • 121
  • 211

2 Answers2

3

When you declare a block type as a parameter to an Objective-C method, the identifier of the block is outside the type. So the syntax looks like this:

@interface IAViewController ()
+(void)tell2:(void(^)(void)) thisBlock;
@end

@implementation IAViewController
- (void)someMethod {
    NSInteger someInt=289456;
    [IAViewController tell2:^{
        NSLog(@"what is this? %i", someInt);
    }];
}

+(void) tell2:(void (^)(void))thisBlock {
    thisBlock();
}
@end
Charles A.
  • 10,685
  • 1
  • 42
  • 39
  • ah, ok so first void = no return type, the second is no args and the third part is the block passed in. What does the (^) carat in the middle mean - or is it just syntax for specifying this is a block? – timpone Aug 11 '13 at 20:03
  • You are correct, the carrot is just the syntax for declaring a block. In other cases (like declaring a block variable for example) you would put the blocks name next to the carrot. It's different here because Objective-C methods always look like `methodSignature:()`, so you don't include the block's identifier with its type. – Charles A. Aug 11 '13 at 20:05
0

Your problem is that you have the text myInt where you should have the block name, and then you are calling a block that takes a void argument with an argument that hasn't been declared anywhere.

You have the method declaration in the @interface correct. Use it again in the @implementation and discard all reference to myInt.

+(void)tell2:(void(^)(void)) thisBlock
{
    // your method implementation
}
Carl Veazey
  • 18,392
  • 8
  • 66
  • 81