本文介绍了致命错误:在展开 Optional 值时意外发现 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 中使用了 UICollectionView 但是当我尝试更改单元格标签的文本时我得到了.

I was using an UICollectionView in Swift but I get when I try to change the text of the cell's label.

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

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("title", forIndexPath: indexPath) as TitleCollectionViewCell
    // Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
    cell.labelTitle.text = "This is a title"
    return cell
}

有人知道吗?

推荐答案

几乎可以肯定,您的重用标识符 "title" 不正确.

Almost certainly, your reuse identifier "title" is incorrect.

我们从dequeueReusableCellWithIdentifierUITableView.h方法签名可以看出,返回类型是一个Implicitly Unwrapped Optional:

We can see from the UITableView.h method signature of dequeueReusableCellWithIdentifier that the return type is an Implicitly Unwrapped Optional:

func dequeueReusableCellWithIdentifier(identifier: String!) -> AnyObject! // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.

这是由AnyObject后的感叹号决定的:

That's determined by the exclamation mark after AnyObject:

    AnyObject!

所以,首先要考虑的是,什么是隐式解包可选"?

So, first thing to consider is, what is an "Implicitly Unwrapped Optional"?

Swift 编程语言告诉我们:

有时从程序的结构中可以清楚地看出,一个可选的将总是有一个值,在该值被第一次设置之后.在这些情况下,它可用于消除检查和解包可选值的需要每次访问它时,因为可以安全地假设它有一个一直以来的价值.

这些类型的选项被定义为隐式解包选项.您可以通过放置一个隐式展开的可选项感叹号 (String!) 而不是问号 (String?)您要设为可选的类型.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

所以,基本上,某些东西可能在某个时候为零,但从某个时候开始就再也不会为零了.因此,我们通过将其作为未包装的值来为自己省去一些麻烦.

So, basically, something that might have been nil at one point, but which from some point on is never nil again. We therefore save ourselves some bother by taking it in as the unwrapped value.

在这种情况下,dequeueReusableCellWithIdentifier 返回这样的值是有意义的.提供的标识符必须已经用于注册单元以供重用.提供不正确的标识符,出队无法找到它,并且运行时返回一个不应该发生的 nil.这是一个致命错误,应用程序崩溃,控制台输出显示:

It makes sense in this case for dequeueReusableCellWithIdentifier to return such a value. The supplied identifier must have already been used to register the cell for reuse. Supply an incorrect identifier, the dequeue can't find it, and the runtime returns a nil that should never happen. It's a fatal error, the app crashes, and the Console output gives:

fatal error: unexpectedly found nil while unwrapping an Optional value

底线:检查您在 .storyboard、Xib 或代码中指定的单元格重用标识符,并确保出列时正确.

这篇关于致命错误:在展开 Optional 值时意外发现 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:50