I have the following selector in a class:
- (SoapRequest*) loginAndConnect: (id) target action: (SEL) action credentials: (WSAcredentials*) arg0 dialoutInfo: (WSAdialoutInfo*) arg1;
I'd like to be able to call it with a block rather than another selector as the action, but I can't find information on how to do this. Something like:
[service loginAndConnect:self credentials:credentials dialoutInfo:dialoutInfo action:^(SoapRequest* aResult) {
// more code here
}];
What's the best way to accomplish this?
UPDATE**
I almost have this working but am getting an exception in objc_release, for the completionBlock object. I'm sure it's something to do with retaining the target, but I'm not sure how to correct it. Here's the current code:
- (BOOL) checkService {
WSAcredentials* credentials = [[WSAcredentials alloc] init];
WSAdialoutInfo* dialoutInfo = [[WSAdialoutInfo alloc] init];
if (!service) {
service = [[WSAWebSocketAdapterService alloc] init];
}
__block SoapRequest* request;
[service loginAndConnectWithCredentials:credentials dialoutInfo:dialoutInfo completionBlock:^(SoapRequestCompletionBlock completionBlock) {
request = (SoapRequest*)completionBlock;
if ([request isKindOfClass: [SoapFault class]]) {
return YES; // we got a response, that's all we care about
}
return NO;
}
];
return YES;
}
Here's my category, very close to what was posted below:
#import "WSAWebSocketAdapterService+BlockExtension.h"
// These objects serve as targets (with action being completed:) for the original object.
// Because we use one for each request we are thread safe.
@interface MyCustomSoapTargetAction : NSObject
@property (copy) SoapRequestCompletionBlock block;
- (void) completed:(id)sender;
@end
@implementation MyCustomSoapTargetAction
- (void) completed:(id)sender
{
// Assuming 'sender' is your SoapRequest
if (_block != nil)
_block(sender);
_block = nil;
}
@end
@implementation WSAWebSocketAdapterService(BlockExtension)
- (SoapRequest*) loginAndConnectWithCredentials:(WSAcredentials*) arg0
dialoutInfo: (WSAdialoutInfo*) arg1
completionBlock:(BOOL (^)(SoapRequestCompletionBlock))completionBlock
{
MyCustomSoapTargetAction *target = [[MyCustomSoapTargetAction alloc] init];
target.block = (SoapRequestCompletionBlock) completionBlock;
//
// Here we assume that target will be retained.
// If that's not the case then we will need to add it to some collection before
// the call below and have the target object remove itself from it after its
// block has been called.
//
return [self loginAndConnect:target action:@selector(completed:) credentials:arg0 dialoutInfo:arg1];
}
@end
Thanks for the help!