2016-03-30 5 views
0

Я работаю над проектом Firebase Swift с использованием CocoaPods.Как исправить: «Неустранимая ошибка: неожиданно найдено нуль при развертывании необязательного значения (lldb)»

Каждый раз, когда я войти основной ViewController, автоматически я получаю EXC_BREAKPOINT ошибка:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Вот некоторые из моих строк кода, где я получил ошибки:

All codes from Joke.swift: 

import Foundation 
import Firebase 


class Joke { 
private var _jokeRef: Firebase! 

private var _jokeKey: String! 
private var _jokeText: String! 


private var _jokeVotes: Int! 


private var _username: String! 

var jokeKey: String { 
    return _jokeKey 
} 

var jokeText: String { 
    return _jokeText 
} 

var jokeVotes: Int { 
    return _jokeVotes //1 
} 

var username: String { 
    return _username 
} 

// Initialize the new Joke 

init(key: String, dictionary: Dictionary<String, AnyObject>) { 
    self._jokeKey = key 

    // Within the Joke, or Key, the following properties are children 

    if let votes = dictionary["votes"] as? Int { 
     self._jokeVotes = votes 
    } 

    if let joke = dictionary["jokeText"] as? String { 
     self._jokeText = joke 
    } 

    if let user = dictionary["author"] as? String { 
     self._username = user 
    } else { 
     self._username = "" 
    } 

    // The above properties are assigned to their key. 

    self._jokeRef = DataService.dataService.JOKE_REF.childByAppendingPath(self._jokeKey) 
} 



// Add or Subtract a Vote from the Joke. 

func addSubtractVote(addVote: Bool) { 

    if addVote { 
     _jokeVotes = _jokeVotes + 1 
    } else { 
     _jokeVotes = _jokeVotes - 1 
    } 

    // Save the new vote total. 

    _jokeRef.childByAppendingPath("votes").setValue(_jokeVotes) 

    } 
} 

В JokeCellTableViewCell.swift :

var joke: Joke! 
............... 

func configureCell(joke: Joke) { 

     self.joke = joke 

     // Set the labels and textView. 

     self.jokeText.text = joke.jokeText 
     self.totalVotesLabel.text = "Total Votes: \(joke.jokeVotes)" // 2 
     self.usernameLabel.text = joke.username 

     // Set "votes" as a child of the current user in Firebase and save the joke's key in votes as a boolean. 

......... 
} 

И в основном ViewController, JokesFee dTableViewController.swift:

var jokes = [Joke]() 

.................... 


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 


    let joke = jokes[indexPath.row] 

    // We are using a custom cell. 

    if let cell = tableView.dequeueReusableCellWithIdentifier("JokeCellTableViewCell") as? JokeCellTableViewCell { 

     // Send the single joke to configureCell() in JokeCellTableViewCell. 

     cell.configureCell(joke) // 3 

     return cell 

    } else { 

     return JokeCellTableViewCell() 

    } 
    ........... 

// 1 // 2 // 3 являются строки кода, где появляются ошибки.

Надеюсь, вы могли бы помочь мне исправить это!

Спасибо заранее!

+0

Что такое '_jokeVotes '? – Hamish

+0

Возможная дубликация [фатальная ошибка: неожиданно найденная нуль при развертывании необязательного значения] (http://stackoverflow.com/questions/24948302/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value) – Fonix

+0

@ originaluser2 'var jokeVotes: Int { return _jokeVotes }' _jokeVotes объявлен как Init –

ответ

1

Ваша проблема в том, что вы четко не определили ожидания класса Joke.

Ваш инициализатор предполагает, что свойства на Joke должны быть необязательными, однако вы используете их, как если бы они не были. Вы должны решить, каким образом вы хотите его принять.

Если свойства могут быть необязательными, я хотел бы предложить что-то вроде этого:

class Joke { 
    private let jokeReference: Firebase 

    let jokeKey: String 

    private(set) var jokeText: String? 

    private(set) var jokeVotes: Int? 

    let username: String 

    // Initialize the new Joke 

    init(key: String, dictionary: Dictionary<String, AnyObject>) { 
     jokeKey = key 

     // Within the Joke, or Key, the following properties are children 

     if let votes = dictionary["votes"] as? Int { 
      jokeVotes = votes 
     } 

     if let joke = dictionary["jokeText"] as? String { 
      jokeText = joke 
     } 

     if let user = dictionary["author"] as? String { 
      username = user 
     } else { 
      username = "" 
     } 

     // The above properties are assigned to their key. 

     jokeReference = DataService.dataService.JOKE_REF.childByAppendingPath(jokeKey) 
    } 
} 

Однако, если свойства не должны быть nil, вам нужно что-то вроде этого:

class Joke { 
    private let jokeReference: Firebase 

    let jokeKey: String 

    let jokeText: String 

    let jokeVotes: Int? 

    let username: String 

    // Initialize the new Joke 

    init?(key: String, dictionary: Dictionary<String, AnyObject>) { 

     jokeKey = key 

     guard let votes = dictionary["votes"] as? Int, 
      joke = dictionary["jokeText"] as? String else { 
       return nil 
     } 

     jokeText = joke 
     jokeVotes = votes 

     if let user = dictionary["author"] as? String { 
      username = user 
     } else { 
      username = "" 
     } 

     // The above properties are assigned to their key. 
     jokeReference = DataService.dataService.JOKE_REF.childByAppendingPath(jokeKey) 
    } 
} 
+0

Вы хотите заменить ее чем-то вроде этого: 'private var jokeRef: Firebase! частный (набор) var jokeKey: String! частный (набор) var jokeText: String! частный (набор) var jokeVotes: Int! частный (набор) var username: String! '? –

+0

@ RazvanJulian Посмотрите на мой отредактированный ответ, пожалуйста. –

Смежные вопросы

 Смежные вопросы