3

I am new to blocks. I am inside a singleton and I do this

void (^ myBlock)() = ^(){ [self doStuff]; };

I receive this error use of undeclared identifier self.

doStuff is a method inside the singleton.

but if this block is declared inside another method, Xcode is OK.

Why is that? thanks.

Duck
  • 34,902
  • 47
  • 248
  • 470

3 Answers3

2

you can define the block in your interface and initialize in any of your methods (including initializers ) in your @implementation file like below:

@interface YourClass {
   void (^ myBlock)();
}

@implementation YourClass

  - (void)yourMethod {
    myBlock = ^(){ [self doStuff]; };
  }


@end
g.revolution
  • 11,962
  • 23
  • 81
  • 107
2

You shouldn't call self directly in a block.
Rather you should make a safe block-pointer from self and access it inside your block.

__block id safeBlockSelf = self;
void (^ myBlock)() = ^(){ [safeBlockSelf doSomething]; };

See How do I avoid capturing self in blocks when implementing an API? for more details.

Community
  • 1
  • 1
yinkou
  • 5,756
  • 2
  • 24
  • 40
0

because every method gets passed self as a hidden param. self is a variable like any other and the block can 'see it/capture it' if in the method

if it is not in a method, self is not a variable set anywhere and the block cant 'see it'

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135