I have two classes. Delegator uses delegation to send its result. Blocker uses blocks in static methods.
Without changing Delegator, how can I elegantly and easily implement methodWithBlock so that the block is called with the result produced by methodWithDelegate?
Delegator:
@class Delegator;
@protocol Delegate <NSObject>
- (void)delegator:(Delegator *)sender producedResult:(int)result;
@end
@interface Delegator : NSObject
@property (weak, nonatomic) id <Delegate> delegate;
- (void)methodWithDelegate;
@end
@implementation Delegator
- (void)methodWithDelegate
{
// Some asynchronous computation resulting in
[self.delegate delegator:self producedResult:42];
}
@end
Blocker:
@interface Blocker : NSObject
+ (void)methodWithBlock:(void(^)(int result))block;
@end
@implementation Blocker
+ (void)methodWithBlock:(void(^)(int result))block
{
// How to call Delegator's methodWithDelegate and return
// the result using block ?
...
}
@end
Explored solutions:
Wrap
Delegatorinto a new class or a category and create a method returning a block, as suggested in this answer. These solutions work but are far too complicated and time-consuming.Make
Blockerconform to the protocolDelegateand keep the block in a property, instantiate it within the methodmethodWithBlock, and call the block when the delegation method is called. This does not work, as there is no strong pointer to this new instance and it gets destroyed.In the previous solution, to avoid losing the instance by lack of a strong pointer, keep a static array of the current instances of
Blockerand delete them in the delegate callback method. Again, this solution works but is too complicated.