意味着它是可能以某種方式施展自我塊可變
像這樣:
- (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