首页 文章

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

提问于
浏览
1

我是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 回答

  • 4

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

    因此,您必须通过删除“弱”关键字来强化它 .

    @IBOutlet var collectionView: UICollectionView!
    

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

  • 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 的子类

相关问题