0

I have some code that queries a class in my Parse database. But sometimes when I log in and get redirected to this view I get a "fatal error: Unexpectedly found nil while unwrapping an Optional value"

Here is my code:

let getPost = PFQuery(className: "Posts")
    getPost.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if let objects = objects {

            self.messages.removeAll(keepCapacity: true)
            self.users.removeAll(keepCapacity: true)
            self.usernames.removeAll(keepCapacity: true)

            for object in objects {

                self.messages.append(object["message"] as! String)

                //////////THE LINE BELOW GIVES ME THE PROBLEM
                self.usernames.append(self.users[object["userId"] as! String]!)

                self.tableView.reloadData()
            }
        }
    }

    self.refresher.endRefreshing()

Anybody know what I've done wrong?

  • 1
    Avoid using `!` (force unwrapping) if you can't guarantee the value won't be nil, use safe unwrapping instead with `if let` and other known techniques: http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language – Eric Aya Jan 14 '16 at 17:42
  • 1
    It's very bad practice to reload the table view in each iteration of the repeat loop. Do it once after the repeat loop. And consider that `findObjectsInBackgroundWithBlock` works asynchronously. – vadian Jan 14 '16 at 17:45
  • Hi guys I have changed my code and added a comment to show which line is giving me the problem – Brad Sutherland Jan 14 '16 at 17:49
  • this snippet is inside of a function - I can include the full function code if you want – Brad Sutherland Jan 14 '16 at 17:49
  • 1
    Right before the repeat loop all items of `self.users` are removed, so `self.users["whatever"]` will always fail. – vadian Jan 14 '16 at 17:53
  • @vadian How do I choose your comment as the correct answer? I have commented out the line self.users.removeAll..... and it seems to be now working! thank you so much! – Brad Sutherland Jan 14 '16 at 17:56
  • @BradSutherland I added an answer. – vadian Jan 14 '16 at 17:58

1 Answers1

1

Right before the repeat loop all items of self.users are removed, so self.users["whatever"] will always fail.

PS: And put self.tableView.reloadData() after the repeat loop.

vadian
  • 274,689
  • 30
  • 353
  • 361