2015-01-25 5 views
2

나는 것을 방지하려면 어떻게해야 는 스위프트 함수 포인터의주기를 유지 방지

는이

import UIKit 
class MagicDataSource:NSObject,UITableViewDatasource { 

    deinit { 
     println("bye mds") 
    } 

    //cant use unowned or weak here 
    var decorator:((cell:CustomCell)->Void)? 

    func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)->UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as CustomCell 

     decorator?(cell) 
     return cell 
    } 

} 

같은 데이터 소스 객체와 같은 뷰 컨트롤러가 상상 스위프트

에 개체로 기능 주위에 전달할 때주기를 계속 보유 당신은 뷰 컨트롤러를 폐기하는 경우, 데이터 소스가 해제하고도보기 통제 할 것되지 않습니다

import UIKit 
class ViewController: UIViewController { 

    var datasource:MagicDataSource? = MagicDataSource() 

    deinit { 
     println("bye ViewCon") 
    } 

    override func viewDidLoad() { 

     super.viewDidLoad() 
     datasource?.decorator = decorateThatThing 
    } 

    func decorateThatThing(cell:CustomCell) { 

     //neither of these two are valid    
     //[unowned self] (cell:CustomCell) in 
     //[weak self] (cell:CustomCell) in 

     cell.theLabel.text = "woot" 

    } 
} 

해당 개체에 대한 강한 심판이있다 (그리고 원)하는 그것은보기 컨트롤러에 decorateThatThing 함수에 대한 강한 참조를 보유하고 있습니다.

당신은주기를 중지하고 ViewController에서이 작업을 수행하여 해제 할 수있는 장식을 얻을 수 있지만, 지저분한 느낌 수

override func viewWillDisappear(animated: Bool) { 
    super.viewWillDisappear(animated) 
    datasource?.decorator = nil 
} 

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    datasource?.decorator = decorateThatThing 
} 

그래서 질문은 내가를 해체하는 것을 방지하기 위해 및/또는 기능 바르를 선언 어떻게입니다 뷰 컨트롤러가 삭제 될 때 연관된 데이터 소스도 해제되도록 수동으로 데이터 소스를 설정하십시오.

+0

않아요 작업을 사용할 수 있습니다. 내가보기 컨트롤러가 데이터 소스를 소유하고 싶습니다. 약한 경우 인스턴스화시 버려집니다 –

답변

3

보다는

datasource.decorator = decorateThatThing 

당신은

datasource.decorator = { [unowned self] cell in 
    self.decorateThatThing(cell) 
} 
+0

'unowned '를 사용하는 FYI는'decorator'가 호출 될 때'self'가 할당 해제되면 충돌을 일으킬 것입니다. [캡처 목록]에서 '약함'을 사용할 수도 있습니다 (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097- CH20-ID57). –

+0

네,'decorator'가 호출되는 동안'self'가 할당 해제 될 가능성이 있다면'weak'을 사용하십시오. 그러나 이것이 가능하지 않다면, '소유하지 않은 사람'을 사용하십시오. '약점'을 사용하는 것은 비싸지는 않지만 무료가 아닙니다. – Rob