iphone - 解包可选值时出错 AND dequeueReusableCellWithIdentifier( :cell identifier)

标签 iphone xcode swift

this is app for search

Not error before app running !

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = UITableViewCell()
    cell = tableView.dequeueReusableCellWithIdentifier("SpotListCell")!

    if(cell.isEqual(NSNull))
    {
        cell = (NSBundle.mainBundle().loadNibNamed("SpotListCell", owner: self, options: nil)[0] as? UITableViewCell)!;
    }


    if tableView == self.tableView {
        cell.textLabel?.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
    } else {
        cell.textLabel?.text = self.filteredPosts[indexPath.row]
    }
    return cell
}

Moment to run apps, searching the error. The following error.

fatal error: unexpectedly found nil while unwrapping an Optional value

(lldb)

Where should be modified? Thank you for reading it. Note I am a Korean high school student.

最佳答案

我猜这行是给你带来麻烦的原因:

cell = tableView.dequeueReusableCellWithIdentifier("SpotListCell")!

您的 TableView 似乎无法为您创建 SpotListCell ,并且由于您添加了 ! ,您强制编译器为您提供值,无论它是 nil 或不。

在下一行中你可以说:

if(cell.isEqual(NSNull))

但是 cell 是 nil 所以你不能向它询问任何东西(而且...NSNull可能不是你要找的东西)。

编辑:更新了我的答案

首先,您应该注册 Nib,以便 UITableView 可以使用它。

  • 为您的 UITableView 创建一个 socket 并连接它:

    @IBOutlet 弱变量 tableView: UITableView!

  • 然后在您的 viewDidLoad() 中您可以执行以下操作: contentTableView.registerNib(UINib(nibName:“SpotListCell”,bundle:nil),forCellReuseIdentifier:“SpotListCell”)

最后,您可以像这样使用您的手机,请注意guard let安全地打开您的手机:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCellWithIdentifier("SpotListCell") else {
        return UITableViewCell()
    }

    //Populate as you did before
    if tableView == self.tableView {
        cell.textLabel?.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
    } else {
       cell.textLabel?.text = self.filteredPosts[indexPath.row]
    }
    return cell    
}

看看这是否更好(我还没有用编译器检查过,所以可能会有错误......我相信编译器会让你知道:))

希望对您有帮助。

关于iphone - 解包可选值时出错 AND dequeueReusableCellWithIdentifier( :cell identifier),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37673469/

相关文章:

ios - 弹出到 Root View Controller 时无法更新导航栏

ios - 在 UIImageView 中剪裁的圆角

iphone - 在 iPhone 应用程序中将 .m4r/.mp3 转换为 .caf/.aiff

iphone - 性能问题 alloc 与 copy

ios - 如何通过 xcode 对边距约束应用乘数?

iphone - 您可以在 IB 中建立一个按钮并以编程方式移动它吗?

iphone - nsurlconnection异步请求

ios - 通过 React Native Firebase 存在 AdMob 时出现 “Linker command” 错误

swift - Xcode从命令行执行 “Test”?

ios - SwiftUI 文本不会扩展为多行