Alamofire在大量请求中释放内存

时间:2015-06-11 02:25:58

标签: swift alamofire

我必须执行大量的POST请求(大于150)并且每个请求都包含大量数据(大约2-4Mb)。

我在这样的for-in循环中执行这样的请求:

    @IBAction func synchToServer(sender: AnyObject) {

    var GlobalUserInitiatedQueue: dispatch_queue_t {
        return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)
    }

    dispatch_async(GlobalUserInitiatedQueue) {

        var serviceGroup = dispatch_group_create()

        var fetchRequest = NSFetchRequest(entityName: "Biography")
        let predicate = NSPredicate(format: "synchronization == nil")
        fetchRequest.predicate = predicate

        if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Biography] {  //This pulls around 150-200 results
            var total = 0
            for l in fetchResults {  //This is where all the requests happen....

                var apiURL = getAppSetting("apiurl") ?? ""  //This variable comes from app settings, global method
                let apikey = getAppSetting("api_key") ?? "" //This variable comes from app settings, global method

                dispatch_group_enter(serviceGroup)
                //In this request l.getJSON returns the data from the entoty as a JSON object
                request(Method.POST, apiURL + "api/biography/" + apikey, parameters: l.getJSON(l), encoding: ParameterEncoding.JSON)
                    .validate(statusCode: [200])
                    .validate(contentType: ["application/json"])
                    .responseJSON{(req,response,data,error) in

                            var json = JSON(data!)

                            l.synch_status = json["status"].stringValue
                            l.synch_message = json["description"].stringValue
                            l.synchronization = NSDate()

                            var err: NSError?

                            if(!managedObjectContext!.save(&err)) {
                                println(err?.localizedDescription)
                            }

                        dispatch_group_leave(serviceGroup)
                }

                total++

                if((total % 10) == 0) {
                    //This waits for the requests to finish in groups of 10 maximum
                    dispatch_group_wait(serviceGroup, DISPATCH_TIME_FOREVER)
                }
            }

            //this waits for the reminder of requests
            dispatch_group_wait(serviceGroup, DISPATCH_TIME_FOREVER)
        }            
    }        
}

但是,这会使每次请求的内存使用量不断上升,直到最终导致应用程序崩溃。有没有办法告诉alamofire释放已经完成的请求的内存?

0 个答案:

没有答案