Swift closure with variable causing memory leak

2019-07-04 01:58发布

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??

2条回答
姐就是有狂的资本
2楼-- · 2019-07-04 02:44

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()
        })
查看更多
beautiful°
3楼-- · 2019-07-04 03:02

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

查看更多
登录 后发表回答