gpt4 book ai didi

objective-c - Obj-C Block 可以自行执行吗?

转载 作者:太空狗 更新时间:2023-10-30 03:36:30 25 4
gpt4 key购买 nike

这是这个问题的扩展: Is it possible to create a category of the "Block" object in Objective-C .

基本上,虽然似乎可以通过 NSObject 或 NSBlock 在 block 上创建类别,但我无法理解 block 如何评估自身。上一题答案中给出的例子:

- (void) doFoo {
//do something awesome with self, a block
//however, you can't do "self()".
//You'll have to cast it to a block-type variable and use that
}

暗示可以以某种方式将 self 转换为 block 变量,但是如何执行 block 本身?例如,假设我在 NSBlock 上做了一个类别并且在一个方法中做了:

NSBlock* selfAsBlock = (NSBlock*)self;

是否有任何消息可以发送到 selfAsBlock 以让 block 评估?

最佳答案

Implies that it is possible to somehow cast self to a block variable

像这样:

- (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));
}

请注意(在大多数情况下)您需要修复 block 签名,以便编译器能够根据目标平台 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;
}

关于objective-c - Obj-C Block 可以自行执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7320214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com