pitou pitou - 1 year ago 90
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() {

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 {


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

textField.placeholder = "Type smothing..."



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")

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:

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download