我正在使用下面的代码从服务器下载图像。此代码编写在 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数据源实现
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
}
}
但它因 _swift_abortRetainUnowned
错误而崩溃。为了防止崩溃,我使用了 [weak self]
和 self?.
但现在的问题是 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
})
如果我注释掉罪魁祸首语句,那么我的内存消耗约为 40Mb,但使用该语句后,内存消耗将达到 200Mb+,并且随着滚动,它会增加。
我不明白该做什么或我错过了什么。谁能帮助我理解并解决这个问题。
最佳答案
unowned
和 weak
不应在您的情况下使用。此闭包不会创建引用循环。
显然,当您使用 unowned
时,您会得到 _swift_abortRetainUnowned
,因为 self
变为 nil
。
由于目标是使用下载的图像更新单元,因此 self
(单元)应该保持事件状态。因此,应该使用对 self 的强烈引用。 self
一旦完成就会被闭包释放。
关于ios - self 已被封闭所俘获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35981064/