2016-02-18 3 views
-1

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

fatal error: unexpectedly found nil while unwrapping an Optional value

enter image description here enter image description here

MealViewController.swift

import UIKit 

class MealViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate { 
// MARK: Properties 

@IBOutlet weak var nameTextField: UITextField! 
@IBOutlet weak var saveButton: UIBarButtonItem! 

    /* 
    This value is either passed by `MealTableViewController` in `prepareForSegue(_:sender:)` 
    or constructed as part of adding a new meal. 
*/ 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if saveButton === sender { 

     let weightInt: Int? = Int(weightInKilos.text!) 
     let dehydrationInt: Int? = Int(percentOfDehydration.text!) 
     let lossesInt: Int? = Int(ongoingLosses.text!) 
     let factorInt: Int? = Int(Factor.text!) 

     let name = nameTextField.text ?? "" 
     let wt = weightInt! 
     let dn = dehydrationInt! 
     let ol = lossesInt! 
     let fr = factorInt! 

     // Set the meal to be passed to MealListTableViewController after the unwind segue. 


     meal = Meal(name: name, wt: wt, dn: dn, ol: ol, fr: fr) 

    } 

    if calcButton === sender { 

    if weightInKilos.text == "" && percentOfDehydration.text == "" && ongoingLosses.text == "" && Factor.text == "" { 

     let alertController = UIAlertController(title: "Fields were left empty.", message: 
      "You left some fields blank! Please make sure that all fields are filled in before tapping 'Calculate'.", preferredStyle: UIAlertControllerStyle.Alert) 
     alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) 

     self.presentViewController(alertController, animated: true, completion: nil) 

    } 

    else { 
     let DestViewController: ftrViewController = segue.destinationViewController as! ftrViewController 

     let weightInt: Int? = Int(weightInKilos.text!) 
     let dehydrationInt: Int? = Int(percentOfDehydration.text!) 
     let lossesInt: Int? = Int(ongoingLosses.text!) 
     let factorInt: Int? = Int(Factor.text!) 

     let lrs24Int = (30 * weightInt! + 70) * factorInt! + weightInt! * dehydrationInt! * 10 + lossesInt! 

     let lrsPerHourint = lrs24Int/24 

     DestViewController.lrsHr = "\(lrsPerHourint)" 
     DestViewController.lrs24Hrs = "\(lrs24Int)" 

    } 

    } 
} 

func textFieldShouldReturn(textField: UITextField) -> Bool { 

    textField.resignFirstResponder() 
    return true 

} 

var meal: Meal? 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Handle the text field’s user input through delegate callbacks. 
    nameTextField.delegate = self 

    // Set up views if editing an existing Meal. 
    if let meal = meal { 
     navigationItem.title = meal.name 
     nameTextField.text = meal.name 

     var weightInt: Int? = Int(weightInKilos.text!) 
     var dehydrationInt: Int? = Int(percentOfDehydration.text!) 
     var lossesInt: Int? = Int(ongoingLosses.text!) 
     var factorInt: Int? = Int(Factor.text!) 

     weightInt = meal.wt 
     dehydrationInt = meal.dn 
     lossesInt = meal.ol 
     factorInt = meal.fr 


     weightInKilos.delegate = self 
     percentOfDehydration.delegate = self 
     ongoingLosses.delegate = self 
     Factor.delegate = self 

     calcButton.layer.cornerRadius = 4; 
     resetbutton.layer.cornerRadius = 4; 

       } 

    // Enable the Save button only if the text field has a valid Meal name. 
    checkValidMealName() 
} 

// MARK: UITextFieldDelegate 


func textFieldDidEndEditing(textField: UITextField) { 
    checkValidMealName() 
    navigationItem.title = textField.text 
} 

func textFieldDidBeginEditing(textField: UITextField) { 
    // Disable the Save button while editing. 
    saveButton.enabled = false 
} 

func checkValidMealName() { 
    // Disable the Save button if the text field is empty. 
    let text = nameTextField.text ?? "" 
    saveButton.enabled = !text.isEmpty 
} 

// MARK: Navigation 

@IBAction func cancel(sender: UIBarButtonItem) { 
    // Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways. 
    let isPresentingInAddMealMode = presentingViewController is UINavigationController 

    if isPresentingInAddMealMode { 
     dismissViewControllerAnimated(true, completion: nil) 
    } else { 
     navigationController!.popViewControllerAnimated(true) 
    } 
} 


// Calculation outlets & actions 
@IBOutlet weak var resetbutton: UIButton! 
@IBOutlet weak var calcButton: UIButton! 

@IBOutlet weak var weightInKilos: UITextField! 
@IBOutlet weak var percentOfDehydration: UITextField! 
@IBOutlet weak var ongoingLosses: UITextField! 
@IBOutlet weak var Factor: UITextField! 

@IBAction func resetButton(sender: AnyObject) { 

    if weightInKilos.text == "" && percentOfDehydration.text == "" && ongoingLosses.text == "" && Factor.text == "" { 
    let alertController = UIAlertController(title: "...", message: 
     "There is no information to reset. Nice try though!", preferredStyle: UIAlertControllerStyle.Alert) 
    alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) 

    self.presentViewController(alertController, animated: true, completion: nil) 
    } 

    else { 
     weightInKilos.text="" 
     percentOfDehydration.text="" 
     ongoingLosses.text="" 
     Factor.text="" 
    } 
} 




} 


class ftrViewController: UIViewController, UITextFieldDelegate { 

@IBOutlet weak var lrs24hours: UILabel! 
@IBOutlet weak var lrsPerHour: UILabel! 


var lrs24Hrs = String() 
var lrsHr = String() 

override func viewDidLoad() { 
    lrs24hours.text = lrs24Hrs 
    lrsPerHour.text = lrsHr 

} 

} 

Meal.swift импорт UIK это

class Meal: NSObject, NSCoding { 
// MARK: Properties 

var name: String 
var wt: Int 
var dn: Int 
var ol: Int 
var fr: Int 


// MARK: Archiving Paths 

static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! 
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals") 

// MARK: Types 

struct PropertyKey { 
    static let nameKey = "name" 
    static let wtKey = "weight" 
    static let dnKey = "dehydration" 
    static let olKey = "ongoinglosses" 
    static let frKey = "factor" 

} 

// MARK: Initialization 

init?(name: String, wt: Int, dn: Int, ol: Int, fr: Int) { 
    // Initialize stored properties. 
    self.name = name 
    self.wt = wt 
    self.dn = dn 
    self.ol = ol 
    self.fr = fr 

    super.init() 

    // Initialization should fail if there is no name or if the rating is negative. 
    if name.isEmpty { 
     return nil 
    } 
} 

// MARK: NSCoding 

func encodeWithCoder(aCoder: NSCoder) { 
    aCoder.encodeObject(name, forKey: PropertyKey.nameKey) 
    aCoder.encodeObject(wt, forKey: PropertyKey.wtKey) 
    aCoder.encodeObject(dn, forKey: PropertyKey.dnKey) 
    aCoder.encodeObject(ol, forKey: PropertyKey.olKey) 
    aCoder.encodeObject(fr, forKey: PropertyKey.frKey) 
} 

required convenience init?(coder aDecoder: NSCoder) { 
    let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String 
    let wt = aDecoder.decodeObjectForKey(PropertyKey.wtKey) as! Int 
    let dn = aDecoder.decodeObjectForKey(PropertyKey.dnKey) as! Int 
    let ol = aDecoder.decodeObjectForKey(PropertyKey.olKey) as! Int 
    let fr = aDecoder.decodeObjectForKey(PropertyKey.frKey) as! Int 

    // Must call designated initializer. 
    self.init(name: name, wt: wt, dn: dn, ol: ol, fr: fr)! 
} 

} 

MealTableViewController.swift

import UIKit 

class MealTableViewController: UITableViewController { 
// MARK: Properties 

var meals = [Meal]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Use the edit button item provided by the table view controller. 
    navigationItem.leftBarButtonItem = editButtonItem() 

    // Load any saved meals, otherwise load sample data. 
    if let savedMeals = loadMeals() { 
     meals += savedMeals 
    } else { 

    } 
} 

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

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return meals.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    // Table view cells are reused and should be dequeued using a cell identifier. 
    let cellIdentifier = "MealTableViewCell" 
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MealTableViewCell 

    // Fetches the appropriate meal for the data source layout. 
    let meal = meals[indexPath.row] 

    cell.nameLabel.text = meal.name 

    return cell 
} 

// Override to support conditional editing of the table view. 
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    // Return false if you do not want the specified item to be editable. 
    return true 
} 


// Override to support editing the table view. 
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == .Delete { 
     // Delete the row from the data source 
     meals.removeAtIndex(indexPath.row) 
     saveMeals() 
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
    } else if editingStyle == .Insert { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    }  
} 


/* 
// Override to support rearranging the table view. 
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { 

} 
*/ 

/* 
// Override to support conditional rearranging of the table view. 
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    // Return false if you do not want the item to be re-orderable. 
    return true 
} 
*/ 


// MARK: - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "ShowDetail" { 
     let mealDetailViewController = segue.destinationViewController as! MealViewController 

     // Get the cell that generated this segue. 
     if let selectedMealCell = sender as? MealTableViewCell { 
      let indexPath = tableView.indexPathForCell(selectedMealCell)! 
      let selectedMeal = meals[indexPath.row] 
      mealDetailViewController.meal = selectedMeal 
     } 
    } 
    else if segue.identifier == "AddItem" { 
     print("Adding new meal.") 
    } 
} 


@IBAction func unwindToMealList(sender: UIStoryboardSegue) { 
    if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal { 
     if let selectedIndexPath = tableView.indexPathForSelectedRow { 
      // Update an existing meal. 
      meals[selectedIndexPath.row] = meal 
      tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) 
     } else { 
      // Add a new meal. 
      let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) 
      meals.append(meal) 
      tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) 
     } 
     // Save the meals. 
     saveMeals() 
    } 
} 

// MARK: NSCoding 

func saveMeals() { 
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path!) 
    if !isSuccessfulSave { 
     print("Failed to save meals...") 
    } 
} 

func loadMeals() -> [Meal]? { 
    return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as! [Meal] 
} 

}

MealTableViewCell.swift

import UIKit 

class MealTableViewCell: UITableViewCell { 
// MARK: Properties 

@IBOutlet weak var nameLabel: UILabel! 


override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
} 

override func setSelected(selected: Bool, animated: Bool) { 
    super.setSelected(selected, animated: animated) 

    // Configure the view for the selected state 
} 

} 
+0

Сообщите нам об ошибке. –

+0

Позвольте мне попытаться выяснить, как это описать ... –

+0

Подсказка: когда когда-либо вы получите этот тип ошибки, добавьте точку прерывания исключения .... https://developer.apple.com/library/ios/recipes/xcode_help -breakpoint_navigator/articles/add_an_exception_breakpoint.html – Jageen

ответ

-1

попробовать этот метод convenience required init?(coder aDecoder: NSCoder)

convenience required init?(coder aDecoder: NSCoder) { 
    if let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as? String, 
     wt = aDecoder.decodeObjectForKey(PropertyKey.wtKey) as? Int, 
     dn = aDecoder.decodeObjectForKey(PropertyKey.dnKey) as? Int, 
     ol = aDecoder.decodeObjectForKey(PropertyKey.olKey) as? Int, 
     fr = aDecoder.decodeObjectForKey(PropertyKey.frKey) as? Int { 
     // Must call designated initializer. 
     self.init(name: name, wt: wt, dn: dn, ol: ol, fr: fr) 
    } else { 
     return nil 
    } 
} 
+0

не работает? – Ethan

+0

Большое вам спасибо! Я вставлял ваш код, и он работает потрясающе! –

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

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