2016-03-14 33 views
0

我正在使用以下代碼從服務器下載映像。此代碼寫在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實現

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   
}) 

如果我註釋掉的罪魁禍首聲明,然後我的記憶中消費量大約爲40兆字節,但這種說法不言而喻200MB +,並滾動它增加。

我無法理解要做什麼或錯過了什麼。任何人都可以幫助我理解和解決這個問題。

+1

請發表您的所有代碼。 – ryantxr

+0

@ryantxr,請參閱編輯的問題。 –

+0

看起來你有一張桌子,每個單元格都有一個下載的圖像。 – ryantxr

回答

0

unownedweak不應該用在你的情況。該閉包不會創建參考週期。

顯然,當您使用unowned時,您將得到_swift_abortRetainUnowned,因爲self變爲nil

由於目標是更新單元格與下載的圖像,self(細胞)應保持活着。因此應該使用強烈的自我引用。一旦完成,將由封閉發佈self

+0

爲什麼我需要保持'自我'活着。沒有必要這樣做。如果該單元正在釋放,則沒有意義更新該單元。 –