ios - self 已被封闭所俘获

标签 ios swift memory-management memory-leaks closures

我正在使用下面的代码从服务器下载图像。此代码编写在 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+,并且随着滚动,它会增加。

我不明白该做什么或我错过了什么。谁能帮助我理解并解决这个问题。

最佳答案

unownedweak 不应在您的情况下使用。此闭包不会创建引用循环。

显然,当您使用 unowned 时,您会得到 _swift_abortRetainUnowned,因为 self 变为 nil

由于目标是使用下载的图像更新单元,因此 self (单元)应该保持事件状态。因此,应该使用对 self 的强烈引用。 self 一旦完成就会被闭包释放。

关于ios - self 已被封闭所俘获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35981064/

相关文章:

ios - 在swift 5中获取目录中的文件名

iOS 亚马逊 S3 SDK : message sent to deallocated instance

iphone - 放置在 UIActionSheet 中时无法输入 UITextFiled

ios - 请求桌面 html NSURLSession

json - map 字典 [字符串 :Any] to class

ios - RxSwift : how do I work with schedulers so I run one observable at a time?

ios - MKAnnotationView 标注的自定义字体

ios - 在 SwiftUI 中检测并转发屏幕上任意位置的点击

memory - 无硬件支持的虚拟内存

c++ - 清除包含 vector 的类的 vector 是否足以清除所有内容?