Reputation: 10585
Consider following code involving SpecialRequest
, which has member result
that is not populated right away:
- (NSArray *)getXboxSizedArray {
SpecialRequest *request = [SpecialRequest request];
request.someParam = 11; //and so forth...
[request start];
}
And say there is a callback for requestFinished
:
- (void)requestFinished:(SpecialRequest *)request {
//hooray!
}
I want to return the value of request.result
, but of course only after the request has completed (which I would know from -(void)requestFinished
. How do I do this?
Edit: Note that I have tried putting a return statement inside a block, and failed miserably.
Edit 1: Here is an example of bad and non working code if you are interested:
- (NSString *)getAllDogFoodBrand {
__unsafe_unretained __block ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"some_url"]];
request.delegate = self;
[request setCompletionBlock:^{
[self.delegate objectControllerDidFinishRequestWithStatus:request.responseStatusMessage];
//return request.responseString; <-- this line makes compiler :(
}];
[request startAsynchronous];
}
Upvotes: 1
Views: 278
Reputation: 11834
Another approach could be to create a wrapper class for your request with a method that accepts a block parameter. The block parameter could be stored in an instance variable (generally a copy
property) and after the request has finished the completion block stored in the instance variable can be called from the -requestFinished:
callback method. This is in my opinion a neater approach compared to using delegates.
Upvotes: 1
Reputation: 17877
You can use for that purposes combination of delegate
and protocol
.
For example, here you could find a small tutorial: The Basics of Protocols and Delegates
Also you could use KVC with KVO. Check here about that approaches here: Key-Value Observing Programming Guide
Upvotes: 0