Hi guys,
I have my fetcher class, which has couple of methods for fetching data from the internet, process them (creates object) and returns that object back to its view controller. I use asynchronous from ASIHTTPRequest.
I want to do the code in this fetcher very code reusable. Therefore I followed an example from ASIHTTPRequest doc for asynchronous loading:
PHP Code:
- (User *)loadUser:{
NSURL *url = [NSURL URLWithString:@"http://something.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request{
NSString *responseString = [request responseString];
//[b]OBJECT CREATION[/b]
}
- (void)requestFailed:(ASIHTTPRequest *)request{
NSError *error = [request error];
}
loadUser method of course doesn't work because there is no way how I can create and return User object. Unless I would have created it in
- (void)requestFinished
ASIHTTPRequest *)request. This would work but only for this particular ONE method loadUser.
Therefore, I have tried to use blocks - I dunno whether it is the best idea or not, but the code looks like this:
PHP Code:
- (User *)loadUser:(int)user_id{
__block User *user;
NSURL *url = [NSURL URLWithString:@"http://something.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
//[b]DATA SERIALIZATION[/b]
user = [[User alloc] initWithUser_id:user_id];
NSLog(@"USER complete: %@", [user name]);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"%@", error);
}];
[request startAsynchronous];
NSLog(@"USER: %@", [user name]);
return user;
}
I have used NSLogs to check the object. In the end of the method, User object is returned null. So I actually get null back to my view controller

. Later on...when
request setCompletionBlock is done, the User object is being created! BUT it is already too late, cause
loadUser method has been executed and returned null to the view controller.
What should I do, if I want to have all request in the same fetcher class? And reuse method
request setCompletionBlock? Or would it be better approach to fetch those requests directly in my view controllers? Thanks in advance for your help