这是一个简化,但我的应用程序有以下方法:
//This is a common function that is used by various functions in my app to send a HTTP Post via NSURLConnection
- (void)sendPostWithURL:(NSString*)url
//This is the NSURLConnection function that has the response data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
//myFunction1: send a HTTP Post and receive response1.json
-(void)myFunction1{
[self sendPostWithURL:@"http://www.somesite.com/response1.json"];
}
//myFunction2: send a HTTP Post and receive response2.json
-(void)myFunction2{
[self sendPostWithURL:@"http://www.somesite.com/response2.json"];
}
正如您所看到的,我有两个函数(myFunction1和myFunction2)共享一个用于发送和接收数据的公共NSURLConnection。
在connectionDidFinishLoading()函数中,如何判断响应是针对myFunction1还是myFunction2?
我有一种可能性,例如请求在json响应数据中,有一个键/值对允许我查看它是哪个响应。但是,我觉得在代码本身中有一种更优雅的方式来做这件事。
任何建议都会很棒!谢谢!
答案 0 :(得分:2)
你称他们为“功能”。如果你开始将它们视为课堂上的“方法”,那么很多方法会更有意义。
您需要将所有NSURLConnection内容封装在一个类中(称为Downloader.m)。 Downloader.m将有方法:sendPostWithUrl和connectionDidFinishLoading。
然后,当您需要下载某些东西时,实例化一个新的下载器实例,并调用它的sendPost方法。每个下载操作都有一个特定的类实例,这些实例应该很容易跟踪。