Is it possible to extend an existing Objective-C Block?

别说谁变了你拦得住时间么 提交于 2019-12-07 08:44:41

问题


I have a class using a Block defined in the header like this:

@property (readwrite, copy) RequestSucceededBlock succeededBlock;

The property succeededBlock is already set with a Block. Is there a way to override this Block with another that still calls the original, similar to class inheritance?

I assume this is not possible, because class inheritance should be used to express things like that. Is it still possible?


回答1:


Assuming you're talking about trying to have a replacement block in a subclass that still calls the superclass block, you can't inject a block into an existing block but you can fake it as follows:

// 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;
}

This is a bit odd though b/c it assumes the superclass has a default block assigned to succeededBlock that you want to dispatch. If your question has a different use in mind please clarify and I'll see if I can update this.

EDIT: added copy to iVar



来源:https://stackoverflow.com/questions/8039204/is-it-possible-to-extend-an-existing-objective-c-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!