Alamofire块使用了大量内存

时间:2018-02-27 14:27:47

标签: ios swift alamofire

class ViewController: UIViewController {
      let defaults = UserDefaults.standard
      var ProfileStatus = ""

      override func viewDidLoad() {
        super.viewDidLoad()

      }
      @IBAction func testingaction(_ sender: Any) {

        if FIRAuth.auth()?.currentUser != nil {
            let login = "URL"
            let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 120
            var Appkey = ""
            var SessionToken = ""
            var UserID = ""


            if let ak = defaults.value(forKey: "AppKey") {
                Appkey = ak as! String
            }
            if let st = defaults.value(forKey: "SessionToken") {
                SessionToken = st as! String
            }
            if let uid = defaults.value(forKey: "UserID") {
                UserID = uid as! String
            }

            let data : [String : Any] = ["AppKey" : Appkey , "SessionToken" : SessionToken , "UserID" : UserID]

            manager.request(login, method: .post, parameters: data, encoding: URLEncoding.default, headers: nil).responseJSON{
                response in

                let json = JSON(response.result.value)
                //print(json)

                if let pstat =  json.dictionaryObject!["ProfileStatus"] {
                    self.ProfileStatus = pstat as! String
                    self.defaults.setValue(pstat, forKey: "ProfileStatus")
                    print(self.defaults.value(forKey: "ProfileStatus")!)
                }

                // This is the block after which I have noticed the spike in the memory usage.

                if self.ProfileStatus == "0" { 


                    self.performSegue(withIdentifier: "status", sender: nil)
                }

                else {

                    self.performSegue(withIdentifier: "homescreen", sender: nil)
                }

            }
        }
        else {
            performSegue(withIdentifier: "test", sender: nil)
        }
    }
}

testingaction是按下按钮时实现的方法。按下按钮后,内存使用量从55MB增加到近593MB。我不知道问题是什么。当检查配置文件状态的值时,我注意到了这个尖峰。

1 个答案:

答案 0 :(得分:0)

我猜你应该在块中使用[weak self]来阻止自我对象的强引用(增加保留计数):

manager.request(login, method: .post, parameters: data, encoding: URLEncoding.default, headers: nil).responseJSON{ 
   [weak self] response in
        let json = JSON(response.result.value)
        //print(json)

        if let pstat =  json.dictionaryObject!["ProfileStatus"] {
            self?.ProfileStatus = pstat as! String
            self?.defaults.setValue(pstat, forKey: "ProfileStatus")
            print(self?.defaults.value(forKey: "ProfileStatus")!)
        }