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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24643522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:17:05  来源:igfitidea点击:

Fatal error: unexpectedly found nil while unwrapping an Optional values

iosswiftuicollectionview

提问by rulilg

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

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

    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
}

Does anyone know about this?

有没有人知道这个?

Screenshot for warning on Console

控制台警告的屏幕截图

采纳答案by Max MacLeod

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

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

We can see from the UITableView.hmethod signature of dequeueReusableCellWithIdentifierthat the return type is an Implicitly Unwrapped Optional:

我们可以从UITableView.h方法签名中dequeueReusableCellWithIdentifier看出,返回类型是一个隐式展开的 Optional

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

That's determined by the exclamation mark after AnyObject:

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

    AnyObject!

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

那么,首先要考虑的是,什么是“隐式展开的可选”?

The Swift Programming Languagetells us:

Swift 编程语言告诉我们:

Sometimes it is clear from a program's structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional's value every time it is accessed, because it can be safely assumed to have a value all of the time.

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.

有时,从程序的结构中可以清楚地看出,在首次设置该值之后,可选项将始终具有一个值。在这些情况下,消除每次访问可选值时检查和解包的需要是有用的,因为可以安全地假设它始终具有值。

这些类型的选项被定义为隐式展开的选项。通过在要设置为可选的类型之后放置一个感叹号 (String!) 而不是问号 (String?),您可以编写一个隐式展开的可选。

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.

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

It makes sense in this case for dequeueReusableCellWithIdentifierto 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:

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

fatal error: unexpectedly found nil while unwrapping an Optional value

Bottom line: check your cell reuse identifier specified in the .storyboard, Xib, or in code, and ensure that it is correct when dequeuing.

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

回答by Connor

You can prevent the crash from happening by safely unwrapping cell.labelTitlewith an if letstatement.

您可以通过cell.labelTitle使用if let语句安全地展开来防止崩溃的发生。

if let label = cell.labelTitle{
    label.text = "This is a title"
}

You will still have to do some debugging to see why you are getting a nil value there though.

你仍然需要做一些调试来看看为什么你在那里得到一个 nil 值。

回答by Ron Fessler

Check if the cell is being registered with self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String). If so, then remove that line of code.

检查单元格是否正在注册self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String)。如果是这样,则删除该行代码。

See this answer for more info: Why is UICollectionViewCell's outlet nil?

有关更多信息,请参阅此答案: Why is UICollectionViewCell's outlet nil?

"If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard."

“如果你使用的是故事板,你不想调用它。它会覆盖你在故事板中的内容。”

回答by greeninaqua

I don't know is it bug or something but your labels and other UIs does not initialized automatically when you use custom cell. You should try this in your UICollectionViewControllerclass. It worked for me.

我不知道这是错误还是什么,但是当您使用自定义单元格时,您的标签和其他 UI 不会自动初始化。你应该在你的UICollectionViewController课堂上尝试这个。它对我有用。

override func viewDidLoad() {
    super.viewDidLoad()

    let nib = UINib(nibName: "<WhateverYourNibName>", bundle: nil)
    self.collectionView.registerNib(nib, forCellReuseIdentifier: "title")
}

回答by iOS Developer

Replace this line cell.labelTitle.text = "This is a title"
with cell.labelTitle?.text = "This is a title"

将此行替换 cell.labelTitle.text = "This is a title"
cell.labelTitle?.text = "This is a title"

回答by Pruthvid

I got his error when i was trying to access UILabel. I forgot to connect the UILabelto IBOutletin Storyboard and that was causing the app to crash with this error!!

我得到了他的错误,当我试图访问UILabel。我忘记在 Storyboard 中连接UILabelIBOutlet,这导致应用程序因此错误而崩溃!!

回答by ClareHuxtable

I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.

我也遇到了这个问题,问题出在视图控制器中。我不确定您的应用程序的结构如何,所以我将解释我发现的内容。我对 xcode 和编码很陌生,所以请耐心等待。

I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.

我试图以编程方式更改 UILabel 上的文本。使用“self.mylabel.text”工作正常,直到我在同一类下添加了另一个不包含该标签的视图控制器。那是我收到您看到的错误的时候。当我添加相同的 UILabel 并将其连接到该附加视图控制器时,错误消失了。

In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.

简而言之,似乎在 Swift 中,分配给同一个类的所有视图控制器都必须引用您在其中的代码,否则会出现错误。如果您有两个具有不同代码的不同视图控制器,请将它们分配给不同的类。这对我有用,希望适用于你正在做的事情。

回答by Kishore Kumar

fatal error: unexpectedly found nil while unwrapping an Optional value

致命错误:在展开可选值时意外发现 nil

  1. Check the IBOutlet collection , because this error will have chance to unconnected uielement object usage.
  1. 检查 IBOutlet 集合,因为此错误将有机会使用未连接的 uielement 对象。

:) hopes it will help for some struggled people .

:) 希望它会帮助一些挣扎的人。

回答by ekeith

I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view sectionset the table view cellto the corresponding identifier name you are using in the program, make sure they match.

我在 Xcode 7.3 上遇到了同样的问题。我的解决方案是确保我的单元格具有正确的重用标识符。在表格视图部分下,将表格视图单元格设置为您在程序中使用的相应标识符名称,确保它们匹配

回答by Abhijeet

Nil Coalescing Operator can be used as well.

也可以使用 Nil Coalescing Operator。

rowName = rowName != nil ?rowName!.stringFromCamelCase():""