Pass Result of ASIHTTPRequest “requestFinished” Back to Originating Method

前提是你 提交于 2019-12-11 18:45:57

问题


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:


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.



来源:https://stackoverflow.com/questions/2878640/pass-result-of-asihttprequest-requestfinished-back-to-originating-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!