在NSArray中存储带参数的块

Spa*_*Dog 3 cocoa-touch ios objective-c-blocks

我知道我可以像块一样定义属性,例如:

self.myProperty = ^(){
   // bla bla bla        
};
Run Code Online (Sandbox Code Playgroud)

存储在数组上

NSArray *arrayOfBlocks = [[NSArray alloc] initWithObject:[self.myProperty copy]];
Run Code Online (Sandbox Code Playgroud)

然后使用执行它

void (^ myblock)() = [arrayOfBlocks objectAtIndex:0];
myblock();
Run Code Online (Sandbox Code Playgroud)

但是如果块有参数怎么办?

我的意思是,像这样一个块:

self.myProperty = ^(id myObject){
   // bla bla bla        
};
Run Code Online (Sandbox Code Playgroud)

我想要的是能够保持这条线不变

void (^ myblock)() = [arrayOfBlocks objectAtIndex:0];
myblock();

// yes, I know I can replace myblock(); with myblock(object);
// but because I have a large number of blocks on this array, I will have to build
// a huge if if if if statements to see what block is being run and change the objects passed
Run Code Online (Sandbox Code Playgroud)

我想要的是将带有参数的块存储在数组中......如下所示:

NSArray *arrayOfBlocks = [[NSArray alloc] initWithObject:[self.myProperty(object?) copy]];
Run Code Online (Sandbox Code Playgroud)

这可能吗?

小智 5

幸运的是,块是一流的值.您可以创建一个工厂方法,该方法返回将使用某个对象调用的块.

typedef void (^CallbackBlock)(void);
- (CallbackBlock)callbackWithNumber:(int)n
{
    return [^{
        NSLog(@"Block called with %d", n);
    } copy];
}
Run Code Online (Sandbox Code Playgroud)

用法:

[mutableArray addObject:[self callbackWithNumber:42]];
[mutableArray addObject:[self callbackWithNumber:1337]];

// later:
CallbackBlock cb = [mutableArray objectAtIndex:0];
cb();
Run Code Online (Sandbox Code Playgroud)