是否可以扩展现有的Objective-C模块? [英] Is it possible to extend an existing Objective-C Block?

查看:85
本文介绍了是否可以扩展现有的Objective-C模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

@property (readwrite, copy) RequestSucceededBlock succeededBlock;

属性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?

推荐答案

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

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

这有点奇怪,尽管b/c假设超类具有要分配给succeededBlock的默认块.如果您的问题有其他用途,请澄清一下,我会看看是否可以更新.

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.

copy添加到iVar

这篇关于是否可以扩展现有的Objective-C模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆