首页 > iOS中[unowned self]的问题

iOS中[unowned self]的问题

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]


这段代码来说,并不需要unowned,虽然闭包持有self的引用,但是self并没有持有闭包的引用,所以不构成循环引用。



可以看下苹果官方文档

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


防止当前VC(self) -> UIAlertController -> 闭包 -> 当前VC的循环引用

另外闭包内的ac参数也应该weak或unowned

【热门文章】
【热门文章】