pitou pitou - 3 months ago 12
Swift Question

Crash when using TableviewController

I'm trying to use a TableViewController but it makes me crazy because I really don't understand my code crashes in one project but not the other.

The same code (copy-pasted) to different XCode project runs successfully.

Here's my code:

import UIKit
class ViewController: UITableViewController {
var listeDeListes = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(ViewController.addItem))

if (NSUserdefault.standartDefault.objectForKey("identity") != nil) {
listeDeListes = NSUserDefaults.standardUserDefaults().arrayForKey("identity")!
}
}

func addItem() {

let alertController = UIAlertController(title: "New Resolution", message: "", preferredStyle: UIAlertControllerStyle.Alert)
let confirmAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default, handler: ({
(_) in

if let field = alertController.textFields![0] as? UITextField {

self.saveItem(field.text!)
self.tableView.reloadData()
}
}))

let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addTextFieldWithConfigurationHandler ({
(textField) in

textField.placeholder = "Type smothing..."

})

alertController.addAction(confirmAction)
alertController.addAction(cancelAction)

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

func saveItem(itemToSave: String) {
let defaults = NSUserDefaults.standardUserDefaults()
//defaults.setInteger(identity, forKey: "identity")

listeDeListes = listeDeListes + [itemToSave]
defaults.setObject(listeDeListes, forKey: "identity")
defaults.synchronize()

}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50
}

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

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

let item = listeDeListes[indexPath.row]

cell.textLabel?.text = item as! String

return cell
}


This code works and does't work at the same time. Please help me to find why and how.

In the the "bad" project" I get this error message:
 image

Answer

You need to register the cell with the same identifier.

Since you're using storyboard to setup your table, in your storyboard select the cell inside your TableViewController then open the Attributes Inspector (⌥⌘4) and write Cell in front of Identifier.