问题
I am trying to implement a long-polling solution in Swift using iOS 8+.
While the solution undoubtedly works and leaves the main thread free for UI interactions, the memory usage climbs continuously so I am obviously doing something wrong. The class I have written is as follows:
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()
}
}
}
}
I have tried profiling the app in Instruments but the results are confusing. I am hoping somebody can point me in the right direction.
Thanks
回答1:
LongPollDelegate is strong so you have a retain cycle. Make it a weak variable.
来源:https://stackoverflow.com/questions/34513887/http-long-polling-in-swift