3

我知道我可以定义一个像块这样的属性,比如:

self.myProperty = ^(){
   // bla bla bla        
};

将其存储在数组中

NSArray *arrayOfBlocks = [[NSArray alloc] initWithObject:[self.myProperty copy]];

然后使用执行它

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

但是如果块有参数呢?

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

self.myProperty = ^(id myObject){
   // bla bla bla        
};

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

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

我想要的是将带有参数的块存储在数组上......像这样:

NSArray *arrayOfBlocks = [[NSArray alloc] initWithObject:[self.myProperty(object?) copy]];

这可能吗?

4

1 回答 1

5

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

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

用法:

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

// later:
CallbackBlock cb = [mutableArray objectAtIndex:0];
cb();
于 2013-05-01T22:50:32.813 回答