问题
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