是否可以扩展现有的Objective-C Block?

时间:2011-11-07 16:12:46

标签: objective-c inheritance objective-c-blocks

我有一个类使用标题中定义的块,如下所示:

@property (readwrite, copy) RequestSucceededBlock succeededBlock;

属性succeededBlock已设置为Block。有没有办法用另一个仍然调用原始块的块来覆盖这个块,类似于类继承?

我认为这是不可能的,因为类继承应该用来表达这样的事情。还有可能吗?

1 个答案:

答案 0 :(得分:3)

假设您正在讨论尝试在仍调用超类块的子类中使用替换块,则无法将块注入现有块,但可以按如下方式伪造它:

// in MySubclass.h
@property (nonatomic, copy) RequestSucceededBlock subclassSucceededBlock;

// in MySubclass.m
- (RequestSucceededBlock)succeededBlock
{
    [return subclassSucceededBlock];
}

- (void)setSucceededBlock:(RequestSucceededBlock)newSucceededBlock
{
    // make sure this conforms to the definition of RequestSucceededBlock
    RequestSucceededBlock combinedBlock = ^{
        dispatch_async(dispatch_get_current_queue(), newSucceededBlock);
        dispatch_async(dispatch_get_current_queue(), [super succeededBlock]);
    };
    subclassSucceededBlock = combinedBlock;
}

虽然b / c它假设超类有一个分配给succeededBlock的默认块你想要分派,但这有点奇怪。如果您的问题有不同的用途,请澄清,我会看看是否可以更新。

编辑:将copy添加到iVar