快速关闭变量并导致内存泄漏 [英] Swift closure with variable causing memory leak
问题描述
我正在调试带有内存泄漏问题的程序. 在ViewController中,当弹出它时,应调用deinit函数.但这没有,所以我尝试通过以下步骤弄清楚.
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.
通过注释很多行,我发现以下几行使ViewController没有取消分配.
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()
})
在我的ViewController中,我将调用api以获取数据,并替换当前的tripPosts列表.我提到的这一行是此行导致泄漏",当我对其进行注释时,调用deinit.所以我认为这是问题的原因.
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.
用于回叫对象-obj.它来自以下代码:
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??
推荐答案
尝试在api.request({在
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()
})
这篇关于快速关闭变量并导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!