我正在尝试使用 iOS 8+ 在 Swift 中实现长轮询解决方案。
虽然该解决方案无疑有效,并且让主线程可以自由进行 UI 交互,但内存使用量不断攀升,所以我显然做错了一些事情。我写的类如下:
enum LongPollError:ErrorType{
case IncorrectlyFormattedUrl
case HttpError
}
public class LongPollingRequest: NSObject {
var GlobalUserInitiatedQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
}
var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.rawValue), 0)
}
var longPollDelegate: LongPollingDelegate
var request: NSURLRequest?
init(delegate:LongPollingDelegate){
longPollDelegate = delegate
}
public func poll(endpointUrl:String) throws -> Void{
let url = NSURL(string: endpointUrl)
if(url == nil){
throw LongPollError.IncorrectlyFormattedUrl
}
request = NSURLRequest(URL: url!)
poll()
}
private func poll(){
dispatch_async(GlobalBackgroundQueue) {
self.longPoll()
}
}
private func longPoll() -> Void{
autoreleasepool{
do{
let urlSession = NSURLSession.sharedSession()
let dataTask = urlSession.dataTaskWithRequest(self.request!, completionHandler: {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if( error == nil ) {
self.longPollDelegate.dataReceived(data)
self.poll()
} else {
self.longPollDelegate.errorReceived()
}
})
dataTask.resume()
}
}
}
}
我尝试在 Instruments 中分析该应用程序,但结果令人困惑。我希望有人能指出我正确的方向。
Thanks
LongPollDelegate 很强大,因此您有一个保留周期。使其成为弱变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)