简体   繁体   中英

Swift closure with variable causing memory leak

I am debugging my program with a memory leak issue. In the ViewController, when it is pop out, the deinit function should be called. But it didnt, so I try to figure it out with the following step.

by commenting many lines, I found that the following lines make the ViewController didnt dealloc.

var api:APIGetList = APIGetList(tripId: trip.id, offsetToken: offsetToken,shouldRemoveAll:self.shouldRemoveAll)
api.request({ (obj, error) -> Void in
    //ingore here
    }, immediateHandler: {[unowned self](obj) -> Void in
        if var tripPosts = obj as? [TripPost]{
            self.tripPosts = tripPosts<--- this line cause the leak
        }
        self.tableView.reloadData()

    }, failHandler: { (errCode, errMsg, error) -> Void in
        self.isLoading = false
        self.refreshControl.endRefreshing()
})

in my ViewController, I will call the api to get data, and replace the current tripPosts list. the line I mentioned as "this line cause the leak", when I comment it, the deinit called. So I think this line is the cause of the problem.

for the call back object - obj. It comes from the following codes:

var tripPosts = [TripPost]()
tripPosts = TripPost.MR_findAll()
immediateHandler(obj: tripPosts)

so what cause the memory leak??

Try putting [weak self] soon after the api.request({ in

  var api:APIGetList = APIGetList(tripId: trip.id, offsetToken: offsetToken,shouldRemoveAll:self.shouldRemoveAll)

        api.request({ [weak self](obj, error) -> Void in
            //ingore here
            }, immediateHandler: {[weak self](obj) -> Void in
                if var tripPosts = obj as? [TripPost]{
                    self.tripPosts = tripPosts<--- this line cause the leak
                }
                self.tableView.reloadData()

            }, failHandler: {[weak self] (errCode, errMsg, error) -> Void in
                self.isLoading = false
                self.refreshControl.endRefreshing()
        })

oh... finally I figure it out. The problem is the line self.tableView.reloadData()<-- and in the cellForTableView I assigned a delegate to cells which is not a weak reference...

so that's is not related to the closure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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