Curtiscowan96 Curtiscowan96 - 6 months ago 15
Swift Question

Swift 2: My code saves the data(The item added shows in the list) but as soon as I force close the app it deletes all data?

Swift 2: My code saves the data(The item added shows in the list) but as soon as I force close the app it deletes all data?
Sorry for the severe lack of comments but it should be self explanatory. Also i'm quite new to programming so please try to answer in simple terms:)

// ViewController.swift
// Fast Cast
//
// Created by curtis cowan on 31/01/2016.
// Copyright © 2016 Curtis Cowan. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

var lists = [NSManagedObject]()


@IBOutlet weak var myTableView: UITableView!

@IBAction func addItem(sender: AnyObject) {
let alert = UIAlertController(title: "New List", message: "Add a new list", preferredStyle: .Alert)

let saveAction = UIAlertAction(title: "Save", style: .Default) { (UIAlertAction) -> Void in

let textField = alert.textFields![0] as UITextField
if textField != "" {

self.saveItem(textField.text!)
self.myTableView.reloadData()
}

}


let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(saveAction)
alert.addAction(cancelAction)

presentViewController(alert, animated: true, completion: nil)
}



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


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let myCell:UITableViewCell = myTableView.dequeueReusableCellWithIdentifier("Prototype1")!

let list = lists[indexPath.row]
print(lists[indexPath.row])
myCell.textLabel?.text = list.valueForKey("listTitle") as? String


return myCell
}



override func viewDidLoad() {
super.viewDidLoad()

self.myTableView.dataSource = self
self.myTableView.delegate = self

}


func saveItem(Saveitem: String)
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext

let entity = NSEntityDescription.entityForName("List", inManagedObjectContext: managedContext)
let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

item.setValue(Saveitem, forKey: "listTitle")

do {
try managedContext.save()
lists.append(item)


}
catch {
print("Error")
}
}



}

Answer

As @Ismail says, you need to load the data you've been saving

Update your viewDidLoad function to look like this

override func viewDidLoad() {
    super.viewDidLoad()

    self.myTableView.dataSource = self
    self.myTableView.delegate = self

    // go get the data

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName:"List")

    // you may need to sort the list
    let sortDescriptor1 = NSSortDescriptor(key: "listTitle", ascending: true)
    let sortDescriptors = [sortDescriptor1]
    fetchRequest.sortDescriptors = sortDescriptors

    var fetchedResults : [NSManagedObject] = []

    do
    {
        fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
    }
    catch
    {
        return
    }

    for list in fetchedResults
    {
        lists.append(list)
    }

    self.myTableView.reloadData()

}

the data you get back will not always be in the order that you saved it, so it's worth thinking about adding a sort predicate