Can I extend an existing Objective-C block?

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

@property (readwrite, copy) RequestSucceededBlock succeededBlock; 

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

I suppose this is not possible because class inheritance should be used to express such things. Is it possible?

+4
source share
1 answer

Assuming you're talking about trying to have a replacement block in a subclass that still calls the superclass block, you cannot insert a block into an existing block, but you can fake it like this:

 // 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 strange, although b / c assumes that the superclass has a default block assigned to succeededBlock that you want to send. If your question has a different meaning, please specify and I will see if I can update it.

EDIT: added copy to iVar

+3
source

Source: https://habr.com/ru/post/1380025/


All Articles