Question

Can somebody please explain to me i need to separate out the declaration and definition of block like given below:

#import <Foundation/Foundation.h>

// Main method
int main(int argc, const char * argv[])
{
    @autoreleasepool {       
       NSLog(@"Hello, World!");            
    }
}

// Working fine. This code is working fine 
- (void) blockSample{

    (void) (^myBLock) (id sender);

    myBlock = ^(id sender){    // It working fine.
        //implementation
    }
    return 0;
}
/* I need it most work like this.*/
// it shows me error
(void) (^myBLock) (id sender);

myBlock = ^(id sender){    // It shows me error of redefinition.
    //implementation
}
Was it helpful?

Solution

You need to provide a type when defining a variable outside of a function. You can achieve that by first defining a type for your block, or declaring and defining the block in one line.

This works for me:

MyClass.h:

#import <Foundation/Foundation.h>

@interface MyClass : NSObject
- (void)myMethod;
@end

MyClass.m

#import "MyClass.h"

typedef void (^MyBlockType) (id sender);
MyBlockType myBlock = ^(id sender) {
    NSLog(@"It works!");
};

@implementation MyClass
- (void)myMethod {
    myBlock(nil);
}

@end

Then, elsewhere...

MyClass *myClass = [MyClass new];
[myClass myMethod]; // Prints "It works!"

I recommend you read Declaring and Creating Blocks in the Blocks Programming Topics.

OTHER TIPS

someVar = someValue; is an assignment statement. Statements are not allowed outside of functions in C. Only definitions are allowed outside of functions. Thus it is a syntax error.

Like

int foo;
foo = 5;

is equally not valid outside of functions.

What you really want to do is initialize the variable when defining it:

void (^myBLock) (id sender) = ^(id sender) {    // It shows me error of redefinition.
    //implementation
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top