2015-06-30 5 views
1

Возможно, некоторые «Про» могут помочь мне с моими проблемами. Я искал долгое время, но я не нашел хорошего ответа.Сохранение/загрузка добавленных строк в таблицу автоматически

Я новый в быстром. Я переделываю свой первый проект ... конечно, ToDo List. Так что мой вопрос в том, как я могу сохранить и загрузить все строки, которые добавлены в tableview автоматически (без «сохранения бутона»). Когда я перезапущу приложение, все данные будут потеряны.

Спасибо за помощь.

Привет из Германии

import UIKit 

класс ListTableViewController: UITableViewController {

var ToDo = [String]() 

var newToDo: String = "" 

@IBAction func cancel(segue:UIStoryboardSegue) { 

} 

@IBAction func done(segue:UIStoryboardSegue) { 

    var DetailVC = segue.sourceViewController as! DetailViewController 
    newToDo = DetailVC.name 


    ToDo.append(newToDo) 
    self.tableView.reloadData() 


} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    self.tableView.editing = true 


    tableView.backgroundColor = UIColor.whiteColor() 


    tableView.separatorColor = UIColor.orangeColor() 

    //tableView.tableFooterView = UIView(frame:CGRectZero) 


} 

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 the number of sections. 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
      // Return the number of rows in the section. 
    return ToDo.count 
} 


override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { 
    let movedObject = self.ToDo[sourceIndexPath.row] 
    ToDo.removeAtIndex(sourceIndexPath.row) 
    ToDo.insert(movedObject, atIndex: destinationIndexPath.row) 
    NSLog("%@", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(ToDo)") 
    // To check for correctness enable: self.tableView.reloadData() 


} 


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

    // Configure the cell... 


    cell.textLabel!.text = ToDo[indexPath.row] 


    //cell.textLabel?.textColor = UIColor.redColor() 


    cell.backgroundColor = UIColor.clearColor() 

    return cell 


} 






override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == UITableViewCellEditingStyle.Delete { 
     ToDo.removeAtIndex(indexPath.row) 
     tableView.deleteRowsAtIndexPaths([indexPath], 
      withRowAnimation: UITableViewRowAnimation.Automatic) 
    } 
} 

}

import UIKit 

класс ListTableViewController: UITableViewController {

var ToDo = [String]() 

var newToDo: String = "" 

@IBAction func cancel(segue:UIStoryboardSegue) { 

} 

@IBAction func done(segue:UIStoryboardSegue) { 

    var DetailVC = segue.sourceViewController as! DetailViewController 
    newToDo = DetailVC.name 


    ToDo.append(newToDo) 
    self.tableView.reloadData() 


} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    self.tableView.editing = true 


    tableView.backgroundColor = UIColor.whiteColor() 


    tableView.separatorColor = UIColor.orangeColor() 

    //tableView.tableFooterView = UIView(frame:CGRectZero) 


} 

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 the number of sections. 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
      // Return the number of rows in the section. 
    return ToDo.count 
} 


override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { 
    let movedObject = self.ToDo[sourceIndexPath.row] 
    ToDo.removeAtIndex(sourceIndexPath.row) 
    ToDo.insert(movedObject, atIndex: destinationIndexPath.row) 
    NSLog("%@", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(ToDo)") 
    // To check for correctness enable: self.tableView.reloadData() 


} 


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

    // Configure the cell... 


    cell.textLabel!.text = ToDo[indexPath.row] 


    //cell.textLabel?.textColor = UIColor.redColor() 


    cell.backgroundColor = UIColor.clearColor() 

    return cell 


} 






override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == UITableViewCellEditingStyle.Delete { 
     ToDo.removeAtIndex(indexPath.row) 
     tableView.deleteRowsAtIndexPaths([indexPath], 
      withRowAnimation: UITableViewRowAnimation.Automatic) 
    } 
} 

}

+0

Можете ли вы показать нам свой код, что вы на самом деле пытались? – planetmaker

ответ

2

Вы не сказали, что вы используете настойчиво хранить список ToDo, и я не вижу его в коде. Вот хорошее объяснение Reddit использования NSUserDefaults, чтобы сделать это с соответствующим обсуждением plists.

http://www.reddit.com/r/swift/comments/28sp3z/whats_the_best_way_to_achieve_persistence_in/

+0

Спасибо за ваш ответ. – Andreas

+0

Спасибо за ваш ответ. Я 't didn понять смысл«persistenly магазин».... Извините за это. Но в какой момент кода мне нужно вставить UserDefaults? Я пробую несколько способов, но ничего не получится. Я только добавлю новые ToDos в Table View. Они также должны быть сохранены, когда я закрываю приложение и загружаю, когда я снова запустил приложение. В противном случае приложение бесполезно ....: o) – Andreas

+0

Действительно, вы хотите сохранить их между запусками приложений - вот что значит «настойчиво хранить». :-) – lnq

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