Question

I just start learning Objective-C. I got an error when trying to make very small Objective-c Block example. It always shows "expected identifier or '(' before '^' token" errors?. COULD YOU PLEASE TELL ME WHERE DID I MAKE WRONG?

#import <Foundation/Foundation.h>

@interface Block:NSObject
 - (void) printAdd;
@end

@implementation Block   
    void (^addition) (int, int)  =  ^(int left, int right) {
        NSLog(@"Total is: %d\n", left + right); 
    };

  -(void) printAdd {
       NSLog(@"Test");
        addition(12, 13);
    }
@end

int main() {
      Block* myBlock = [[Block alloc] init];
      [myBlock printAdd];
      return 0;
}
Was it helpful?

Solution

The "official" GCC does not support Objective-C blocks, compare Are Objective-C blocks supported by compilers on Linux?, so you should use clang. You also need clang to take advantage of other Objective-C features like "Automatic Reference Counting".


Old answer: That is valid Objective-C code.

My guess: You compiled that as a C program (main.c). Renaming the source file to main.m should solve the problem.

Note that generally, main() for a Objective-C/Foundation program should establish an "autorelease pool":

int main(int argc, const char * argv[])
{
    @autoreleasepool {
      Block* myBlock = [[Block alloc] init];
      [myBlock printAdd];
    }
    return 0;
}

You will get that code if you create a new "Commmand Line Tool" in Xcode and choose "Type = Foundation".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top