swift致命错误:在展开Optional值时意外发现nil

时间:2014-11-14 07:12:57

标签: ios swift uicollectionview uicollectionviewcell

我是swift的新手,我无法弄清楚如何解决此错误。

我正在创建一个集合视图,这是我的代码:

import UIKit

class FlashViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!

        override func viewDidLoad() {
        super.viewDidLoad()
        // Move on ...
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 90, height: 90)
        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
        collectionView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(collectionView!)
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell
        cell.backgroundColor = UIColor.blackColor()
        cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
        cell.imageView?.image = UIImage(named: "circle")
        return cell
    }
}

每次运行时,self.collectionView.dataSource = self行都会突出显示,我会收到上述错误。

2 个答案:

答案 0 :(得分:4)

当您使用弱引用时,您的集合视图在调用之前已发布。

所以你必须通过删除“弱”关键字来强化它。

@IBOutlet var collectionView: UICollectionView!

或者让它以另一种方式留在记忆中。

答案 1 :(得分:0)

...

collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

// because collectionView is a weak variable, it will be released here
self.collectionView.dataSource = self // error, collectionView is nil

...

正如@Vitaliy1所说,你可以使collectionView成为一个强引用,或者在将它添加到视图层次结构之前使用局部变量来挖洞。

...

let collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self

...

view.addSubview(collectionView)
// view establishes a strong reference to collectionView,
// so you can reference it until it is removed from the view hierarchy.
self.collectionView = collectionView

或者,为什么不使用UICollectionViewController

的子类