简体   繁体   English

加载tableView时解开可选值时意外发现nil

[英]Unexpectedly found nil while unwrapping an optional value when loading tableView

I've been on stack for a while now but never needed to ask a question as I've always found the answers after some searching, but now I'm stuck for real. 我已经有一段时间了,但是我从来不需要问一个问题,因为经过一番搜索之后,我总是能找到答案,但是现在我还是坚持到底。 I've been searching around and going through some trial and error for an answer and I keeping getting the same error. 我一直在寻找答案,并经历了一些试验和错误,然后不断遇到相同的错误。 I'm basically making a profile page with a tableView on the bottom half of the screen. 我基本上是在屏幕的下半部分创建一个带有tableView的配置文件页面。 The top half is loading fine filling in the current user's information. 上半部分正在加载当前用户的信息。 All connections to the view controller and cell view controller seem good. 与视图控制器和单元格视图控制器的所有连接似乎都很好。 The table view, however, will appear with no data and crash while loading with the fatal error: 但是,加载致命错误时,表视图将不显示任何数据并且崩溃:

unexpectedly found nil while unwrapping an optional value. 展开可选值时意外发现nil。

I also believe the cellForRowAtIndexPath is not being called at all because "test" is not printing to the logs. 我还认为,根本不会调用cellForRowAtIndexPath ,因为“测试”没有打印到日志中。

I'm using the latest versions of Swift and Parse. 我正在使用Swift和Parse的最新版本。

I'm relatively new to swift so I'll go ahead and post my entire code here and any help at all is appreciated. 我是新手,所以我会继续在这里发布我的整个代码,对您的任何帮助都将不胜感激。

import UIKit
import Parse
import ParseUI

class profileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


@IBOutlet var tableView: UITableView!
@IBOutlet var profilePic: UIImageView!
@IBOutlet var userName: UILabel!
@IBOutlet var userBio: UILabel!
var image: PFFile!
var username = String()
var userbio = String()
var content = [String]()


@IBAction func logout(sender: AnyObject) {
    PFUser.logOut()
    let Login = storyboard?.instantiateViewControllerWithIdentifier("ViewController")
    self.presentViewController(Login!, animated: true, completion: nil)

}

override func viewDidLoad() {
    super.viewDidLoad()


    profilePic.layer.borderWidth = 1
    profilePic.layer.masksToBounds = false
    profilePic.layer.borderColor = UIColor.blackColor().CGColor
    profilePic.layer.cornerRadius = profilePic.frame.height/2
    profilePic.clipsToBounds = true


    tableView.delegate = self
    tableView.dataSource = self


    self.tableView.rowHeight = 80


    self.hideKeyboardWhenTappedAround()

    if let nameQuery = PFUser.currentUser()!["name"] as? String {
        username = nameQuery
    }

    if PFUser.currentUser()!["bio"] != nil {
    if let bioQuery = PFUser.currentUser()!["bio"] as? String {
        userbio = bioQuery
    }
    }

    if PFUser.currentUser()!["icon"] != nil {
    if let iconQuery = PFUser.currentUser()!["icon"] as? PFFile {
        image = iconQuery
    }
    }



    self.userName.text = username
    self.userBio.text = userbio

    if image != nil {
    self.image.getDataInBackgroundWithBlock { (data, error) -> Void in


        if let downIcon = UIImage(data: data!) {


            self.profilePic.image = downIcon

        }
        }

    }


    // Do any additional setup after loading the view.

    var postsQuery = PFQuery(className: "Posts")

    postsQuery.whereKey("username", equalTo: username)

    postsQuery.findObjectsInBackgroundWithBlock( { (posts, error) -> Void in

        if error == nil {

            if let objects = posts {
                self.content.removeAll(keepCapacity: true)

                for object in objects {
                    if object["postText"] != nil {
                        self.content.append(object["postText"] as! String)
                    }
                    self.tableView.reloadData()
                }
            }
        }

    })

}




override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    print(content.count)
    return content.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let profCell = self.tableView.dequeueReusableCellWithIdentifier("profCell", forIndexPath: indexPath) as! profTableViewCell

    print("test")

    profCell.userPic.layer.borderWidth = 1
    profCell.userPic.layer.masksToBounds = false
    profCell.userPic.layer.borderColor = UIColor.blackColor().CGColor
    profCell.userPic.layer.cornerRadius = profCell.userPic.frame.height/2
    profCell.userPic.clipsToBounds = true


    profCell.userPic.image = self.profilePic.image
    profCell.name.text = self.username




    profCell.content.text = content[indexPath.row]



    return profCell
}

}

I let it sit for a few days and I came back to realize a very dumb mistake I made. 我让它坐了几天,然后我回来意识到自己犯了一个非常愚蠢的错误。 I working with around 15 view controllers right now and realized I had a duplicate of the one I posted above with the same name. 我现在与大约15个视图控制器一起工作,意识到我已经复制了上面发布的同名控制器。 I now understand why you say working with storyboards is very sticky. 现在,我明白了为什么您说使用故事板非常棘手。 Though, I did not need it, I appreciate the help and I can say I learned a few things. 虽然我不需要它,但我感谢您的帮助,可以说我学到了一些东西。

You probably need to register the class you are using for the custom UITableViewCell: 您可能需要注册用于自定义UITableViewCell的类:

self.tableView.registerClass(profTableViewCell.self, forCellReuseIdentifier: "profCell") 

Unless you're using prototyped cells in IB, this registration isn't done automatically for you. 除非您在IB中使用原型单元,否则不会自动为您完成此注册。

As such when you call the dequeue method (with the ! forced unwrap) you're going to have issues. 这样,当您调用出队方法(使用!强制展开)时,您将遇到问题。 The dequeueReusableCellWithIdentifier:forIndexPath: asserts if you didn't register a class or nib for the identifier. dequeueReusableCellWithIdentifier:forIndexPath:断言是否未为标识符注册类或笔尖。 when you register a class, this always returns a cell. 当您注册一个类时,它总是返回一个单元格。

The older ( dequeueReusableCellWithIdentifier: ) version returns nil in that case, and you can then create your own cell. 在这种情况下,较早的版本( dequeueReusableCellWithIdentifier:返回nil,然后您可以创建自己的单元格。

You should use a ? 您应该使用? during the as cast to avoid the crash, although you'll get no cells! as cast期间避免崩溃,尽管您不会获得任何单元格!

One other reminder, you should always use capitals for a class name, ProfTableViewCell not profTableViewCell , it's just good pratice. 另一个提醒是,您应始终对类名称使用大写字母, ProfTableViewCell而不是profTableViewCell ,这只是一个好profTableViewCell

Much more information here in the top answer by iOS genius Rob Mayoff: Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath: iOS天才罗布·梅奥夫(Rob Mayoff)的最佳回答中提供了更多信息: dequeueReusableCellWithIdentifier:forIndexPath中的断言失败:

You have to create a simple NSObject Class with image, username and userbio as optional values. 您必须创建一个简单的NSObject类,并将图像,用户名和userbio作为可选值。 Then you have to declare in your profileviewcontroller a var like this: 然后,您必须在profileviewcontroller中声明一个这样的变量:

var allProfiles = [yourNSObjectClass]()

In your cellForRowAtIndexPath add: 在您的cellForRowAtIndexPath中添加:

let profile = yourNSObjectClass()
profile = allProfiles[indexPath.row]

cell.username.text = profile.username

And go on. 继续吧

Use also this: 也使用此:

   dispatch_async(dispatch_get_main_queue(), {
                self.tableView.reloadData()
            })

instead of this: 代替这个:

self.tableView.reloadData()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 致命错误:在Tableview中展开Optional值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value in Tableview Swift在TableView中展开Optional值时意外发现nil - Swift unexpectedly found nil while unwrapping an Optional value in TableView 致命错误:选择tableView单元格时,在展开可选值swift时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value swift When Selecting tableView Cells 展开Optional值时意外发现nil - unexpectedly found nil while unwrapping an Optional value 展开可选的value()时意外找到nil - Unexpectedly found nil while unwrapping an Optional value() 添加UINavigation时,“在展开可选值时意外发现nil” - “Unexpectedly found nil while unwrapping an Optional value” When UINavigation is added 展开Optional值时意外发现nil - Unexpectedly found nil when unwrapping an Optional value 转换为tableview的图像会产生“在展开可选包时意外找到nil” - converted image for tableview yielding “unexpectedly found nil while unwrapping optional” 展开可选值访问tableView单元格时意外发现nil - unexpectedly found nil while unwrapping an Optional values access tableView Cell 值不是nil,但是在展开Optional值时意外发现nil - value is not nil but getting unexpectedly found nil while unwrapping an Optional value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM