简体   繁体   English

Objective-c(iOS)中的常见HTTP请求委托模式

[英]Common HTTP request delegate pattern in Objective-c (iOS)

I have a view controller "myViewController" that makes HTTP requests. 我有一个发出HTTP请求的视图控制器“ myViewController”。 I set the request's delegates to self (the instance of myViewController). 我将请求的委托设置为self (myViewController的实例)。 Everything works fine until I pop myViewController off the navigation stack before a request returns. 一切正常,直到我在请求返回之前将myViewController从导航堆栈中弹出为止。 In this case the request tries to send a message to the dealloc'd myViewController (which causes my app to crash). 在这种情况下,请求尝试将消息发送到已取消分配的myViewController(这将导致我的应用程序崩溃)。

Currently I'm patching/solving this problem by setting the delegate of all requests to nil in myViewController's dealloc method. 当前,我正在通过在myViewController的dealloc方法中将所有请求的委托设置为nil来修补/解决此问题。 What's a better way to do this? 有什么更好的方法?

Perhaps a singleton could be responsible for handling all HTTP requests? 也许一个人可能负责处理所有HTTP请求?

A while ago I had this same problem for UIWebView delegate events. 不久前,我对于UIWebView委托事件也遇到了同样的问题。 The solution is to keep track of all outgoing HTTP requests within your myViewController . 解决方案是跟踪myViewController中所有传出的HTTP请求。 So, keep an instance variable called mutableRequests onto which you add every request that you send. 因此,保留一个名为mutableRequests的实例变量,您将在其中添加每个发送的请求。 It will probably also be a good idea to remove requests from this array once they are finished. 完成请求后,从此数组中删除请求也可能是一个好主意。

In the -viewWillUnload method, simply enumerate through mutableRequests and cancel every request. -viewWillUnload方法中,只需枚举mutableRequests并取消每个请求。 This will not only allow you to cancel all requests before your view is deallocated, but it will also help you respect the release/retain programming model by retaining all of the objects in an array while they are in use. 这不仅使您可以在取消分配视图之前取消所有请求,而且还可以通过在使用对象时将所有对象保留在数组中来帮助您遵守发布/保留编程模型。

Depends on what you're view controller is doing. 取决于您正在查看的控制器正在执行的操作。 If the requests are only relevant in that VC, then do what Alex is suggesting. 如果请求仅与该VC相关,则执行Alex的建议。 If your app revolves around the requests (central part of functionality), you'll probably want that singleton. 如果您的应用围绕请求(功能的中心部分)运行,则可能需要该单例。 You'd probably also want a common delegate that all your view controllers implement, so that whatever is the present view controller can handle your delegate call. 您可能还希望所有视图控制器都实现一个公共委托,以便当前的视图控制器可以处理您的委托调用。 Obviously, your request-handling singleton will serve as the actual delegate of your requests, and call your delegate methods as necessary. 显然,你的请求处理单将作为您的请求的实际代表,并调用你的委托方法是必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM