Reputation: 35953
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.
Upvotes: 3
Views: 4204
Reputation: 5766
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.
Upvotes: 2
Reputation: 50099
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'
Upvotes: 0
Reputation: 12262
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
Upvotes: 2