[英]Self has captured by closure
I am using below code to download image from server. 我正在使用下面的代码从服务器下载图像。 This code is written under UserCell
class, which is a subclass of UITableViewCell
. 这段代码是在UserCell
类下UserCell
该类是UITableViewCell
的子类。
class UserCell: UITableViewCell {
@IBOutlet weak var profileImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
//calling related methods
}
/*
* Other stuffs *
*/
func refreshImage(fileURL: NSURL?) {
unowned let unownedSelf = self
DownloadManager.download(fileURL: imageURL!, completion: {(filePath) -> (Void) in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
unownedSelf.profileImage.image = UIImage(contentsOfFile: filePath.path!)
})
}, error: { (error) -> (Void) in
// Handle error
})
}
}
UITableView Datasource implementation UITableView数据源实现
class Friends: UIViewController {
/*
* Other stuffs *
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reusableIdentifier = "identifier"
let userObject = arrUsers[indexPath.row] //arrUsers is my array of users
let cell = tableView.dequeueReusableCellWithIdentifier(reusableIdentifier, forIndexPath: indexPath) as! UserCell
cell.refreshImage(userObject.image)
return cell
}
}
But it crash with _swift_abortRetainUnowned
error. 但是它因_swift_abortRetainUnowned
错误而崩溃。 To prevent the crash I used [weak self]
and self?.
为了防止崩溃,我使用了[weak self]
和self?.
But now the problem is self
is not being released. 但是现在的问题是self
没有被释放。
DownloadManager.download(fileURL: imageURL!, completion: { [weak self] (filePath) -> (Void) in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// culprit statement
self?.profileImage.image = UIImage(contentsOfFile: filePath.path!)
})
}, error: { (error) -> (Void) in
// Handle error
})
If I comment out the culprit statement then my memory consumption is around 40Mb but with that statement it goes 200Mb+ and with the scroll it increased. 如果我注释掉“罪魁祸首”语句,那么我的内存消耗约为40Mb,但是使用该语句,它将达到200Mb +,随着滚动的增加,它会增加。
I am not able to understand what to do or what point I missed. 我不知道该怎么办或错过了什么要点。 Can anybody please help me to understand and solve this problem. 谁能帮我理解和解决这个问题。
unowned
and weak
should not be used in your case. 在您的情况下,不应使用unowned
weak
。 This closure does not create a reference cycle. 此关闭不会创建参考循环。
Obviously, when you use unowned
you get the _swift_abortRetainUnowned
because self
becomes nil
. 很显然,当你使用unowned
,你得到_swift_abortRetainUnowned
因为self
成为nil
。
Since the goal is to update the cell with downloaded image, self
(the cell) should be kept alive. 由于目标是使用下载的映像更新单元,因此应保持self
(单元)的生命。 Thus a strong reference to self should be used. 因此,应该强烈引用自我。 self
will be released by the closure as soon as it finishes. 封闭完成后, self
将被封闭释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.