ios - 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?

标签 ios swift core-data

Swift 2:我的代码保存了数据(添加的项目显示在列表中),但是一旦我强制关闭应用程序,它就会删除所有数据? 很抱歉严重缺乏评论,但它应该是不言自明的。另外,我对编程很陌生,所以请尝试用简单的术语回答:)

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



}

最佳答案

正如@Ismail所说,您需要加载您一直保存的数据

更新你的 viewDidLoad 函数,如下所示

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

}

您返回的数据并不总是按照您保存的顺序排列,因此值得考虑添加排序谓词

关于ios - 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?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35159176/

相关文章:

iphone - NSFetchedResultsController 刷新重新获取?

ios - UICollectionView 和 UICollectionViewLayout 的关系?

ios - 在 UIView 中循环遍历 UIButtons

ios - 如何让我的简单对象符合 Swift 中的 NSManagedObject 和 NSCoding?

swift - 在 Swift 中向每一行添加值,但在行出队和重用时不添加值

ios - CNContactStoreDidChangeNotification 被多次触发

cocoa - 从 AppDelegate 获取 ManagedObjectContext

ios - 如何按属性过滤模型?

ios - 尝试使用 CALayers 制作水龙头滴水的动画

ios - Xcode 6 Swift - 显示本地 PDF