objective-c - iOS中[unowned self]的问题
天蓬老师
天蓬老师 2017-04-17 17:43:18
0
3
361
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let person = people[indexPath.item]

    let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .Alert)
    ac.addTextFieldWithConfigurationHandler(nil)

    ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

    ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
        let newName = ac.textFields![0]
        person.name = newName.text!

        self.collectionView.reloadData()
    })

    presentViewController(ac, animated: true, completion: nil)
}

在上面这段代码中为什么需要[unowned self]

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

모든 응답(3)
迷茫

当前VC(self) -> UIAlertController -> 闭包 -> 当前VC

의 순환 참조 방지

또한 클로저 내의 ac 매개변수도 약하거나 소유되지 않아야 합니다

刘奇

Apple의 공식 문서를 확인하실 수 있습니다

developer.apple.com/library
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20 -ID48

洪涛

이 코드의 경우 unowned은 필요하지 않습니다. 클로저는 self에 대한 참조를 보유하지만 self은 클로저에 대한 참조를 보유하지 않으므로 순환 참조를 구성하지 않습니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿