0
votes

I have a method (getAllTeams:) that initiates an HTTP request using the ASIHTTPRequest library.

NSURL *httpURL = [[[NSURL alloc] initWithString:@"/api/teams" relativeToURL:webServiceURL] autorelease];

ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:httpURL] autorelease];
[request setDelegate:self];
[request startAsynchronous];

What I'd like to be able to do is call [WebService getAllTeams] and have it return the results in an NSArray. At the moment, getAllTeams doesn't return anything because the HTTP response is evaluated in the requestFinished: method.

Ideally I'd want to be able to call [WebService getAllTeams], wait for the response, and dump it into an NSArray. I don't want to create properties because this is disposable class (meaning it doesn't store any values, just retrieves values), and multiple methods are going to be using the same requestFinished (all of them returning an array).

I've read up a bit on delegates, and NSNotifications, but I'm not sure if either of them are the best approach. I found this snippet about implementing callbacks by passing a selector as a parameter, but it didn't pan out (since requestFinished fires independently).

Any suggestions? I'd appreciate even just to be pointed in the right direction.

NSArray *teams = [[WebService alloc] getAllTeams]; (currently doesn't work, because getAllTeams doesn't return anything, but requestFinished does. I want to get the result of requestFinished and pass it back to getAllTeams:)

1

1 Answers

0
votes

Send a reference to the originating class instance along with the call:

[WebService getAllTeams:self];

Then modify -getAllTeams to accept a reference to the originating instance:

- (void) getAllTeams:(id)sender {
    // ...
    [request setDelegate:sender];
    // ...
}

Your originating instance will be responsible for handling the response and cleaning up memory.