意味着它是可能以某种方式施展自我块可变
像这样:
- (void)doFoo {
// Assume the block receives an int, returns an int,
// and cast self to the corresponding block type
int (^selfBlock)(int) = (int (^)(int))self;
// Call itself and print the return value
printf("in doFoo: %d\n", selfBlock(42));
}
注意,(在大多数情况下),你需要修复的块签名,以便编译器能够根据目标平台ABI建立呼叫站点。在上面的示例中,签名是返回类型int
,类型为int
的单个参数。
完整的例子就是:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Foo : NSObject
- (void)doFoo;
@end
@implementation Foo
- (void)doFoo {
// Assume the block receives an int, returns an int,
// and cast self to the corresponding block type
int (^selfBlock)(int) = (int (^)(int))self;
// Call itself and print the return value
printf("in doFoo: %d\n", selfBlock(42));
}
@end
int main(void) {
[NSAutoreleasePool new];
// From Dave's answer
Method m = class_getInstanceMethod([Foo class], @selector(doFoo));
IMP doFoo = method_getImplementation(m);
const char *type = method_getTypeEncoding(m);
Class nsblock = NSClassFromString(@"NSBlock");
class_addMethod(nsblock, @selector(doFoo), doFoo, type);
// A block that receives an int, returns an int
int (^doubler)(int) = ^int(int someNumber){ return someNumber + someNumber; };
// Call the category method which in turn calls itself (the block)
[doubler doFoo];
return 0;
}
当然可以。你可以在这里找到更多(已经在SO)http://stackoverflow.com/questions/4824613/is-there-a-self-pointer-for-blocks –
我不明白如何解决这个问题。这个答案似乎集中在如何从自己的块定义中调用块。我正在讨论从块对象本身评估块。只是为了更具体一点,我希望能够通过这个方法来添加方法(NSObject或NSBlock)来实现基于块的控制流(即[Block whileTrueDo:block])。要做到这一点,我需要块在方法中重新评估自己。 – donalbain