iOS10& Switt3 - 核心数据不保存也不返回结果

时间:2017-03-18 15:41:49

标签: core-data swift3 ios10

我正在使用Core Data构建应用程序。到目前为止,它一直对我有用。最近,     我没有结果。没有错误。似乎没有数据持续存在。有没有人遇到过这种奇怪的故障?

我的viewcontroller:显示联系人列表

    import UIKit
    import CoreData

    class ContactsTableViewController: UITableViewController {

    @IBAction func addContactAction(_ sender: AnyObject) {
        alertDialog()
    }


    let identifier = "contactCell"
    var contacts:[String] = [String]()
    var managedContext:NSManagedObjectContext?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        managedContext =  (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        addContacts(numContacts: 30);
    }


    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        fetchContacts("") { (list) in
            for i in 0..<list.count {
                contacts.append(list[i].value(forKey:"name")! as! String)
            }
            tableView.reloadData()
        }
    }

    func alertDialog() {
        //It takes the title and the alert message and prefferred style
        let alertController = UIAlertController(title: "Add Contact", message: "", preferredStyle: .alert)


        alertController.addTextField { (textField) in
            textField.placeholder = "contact"

        }
        let defaultAction = UIAlertAction(title: "Add", style: .default) { (UIAlertAction) in

            let textField = alertController.textFields![0]
            self.addContact(name: textField.text!)
            self.tableView.reloadData()

        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        //now we are adding the default action to our alertcontroller
        alertController.addAction(defaultAction)
        alertController.addAction(cancelAction)

        //and finally presenting our alert using this method
        present(alertController, animated: true, completion: nil)
    }
      }




     extension ContactsTableViewController {

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)

        // Configure the cell...
        cell.textLabel?.text = contacts[indexPath.row]

        return cell
    }

    // MARK: - Table view delegate
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {

            let contactToDelete = contacts[indexPath.row]
            deleteContact(contactToDelete)
            contacts.remove(at: (indexPath as NSIndexPath).row)
            tableView.deleteRows(at: [indexPath], with: .fade)

        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
}

extension ContactsTableViewController {

    func addContacts(numContacts:Int) {

        for i in 1..<numContacts {

            let contact = NSEntityDescription.insertNewObject(forEntityName: "Contact", into: managedContext!) as! Contact

            contact.setValue("name \(i)", forKeyPath: "name")

            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do {
                try managedContext?.save()

                print("\(contact.value(forKeyPath: "name") as! String)) successfully saved")

            } catch  {

                fatalError("Failure to save context: \(error)")

            }
        }

        self.tableView.reloadData()
    }

    func addContact(name:String) {

        let contact = NSEntityDescription.insertNewObject(forEntityName: "Contact", into: managedContext!) as! Contact

        contact.setValue(name, forKeyPath: "name")

        (UIApplication.shared.delegate as! AppDelegate).saveContext()

        do {
            try managedContext?.save()

            print("\(contact.value(forKeyPath: "name") as! String)!) successfully saved")
        } catch  {
            fatalError("Failure to save context: \(error)")
        }

        self.tableView.reloadData()
    }

    func fetchContacts(_ predicate:String, completion:(_ array:[Contact]) -> ()) {

        var arr:[Contact] = [Contact]()


        let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Contact")

        request.predicate = NSPredicate(format: "name = %@", predicate)

        do {

            let results  =  try managedContext?.fetch(request) as! [Contact]

            for result in results {

                let name = (result as AnyObject).value(forKey: "name") as? String

                arr.append(result)

            } //for

            print(results)

            completion(arr as [Contact])

        } catch {
            print("error fetching results")
        } //do
    }

    func deleteContact(_ name:String) {

        fetchContacts(name) { (array) -> () in

            for result in array {

                let aContact = (result as AnyObject).value(forKey: "name") as? String

                if aContact == name {

                    //delete
                    self.managedContext?.delete(result)

                    //save
                    do {
                        try self.managedContext!.save()
                        print("\(aContact) deleted")
                    } catch {

                        print("error deleting contact")
                    } //do

                } // if
            } //for
        }
    }

}

我的AppDelegate.swift

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "ContactLists_coreData")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

生成的实体类

import Foundation
import CoreData


extension Contact {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Contact> {
        return NSFetchRequest<Contact>(entityName: "Contact");
    }

    @NSManaged public var name: String?

}

数据模型。非常简单

<img src="https://drive.google.com/file/d/0B1Usy68B1DzYLUduNTlCY092VEk/view" width="1970" height="1084">

数据源和单元标识符正确连接

1 个答案:

答案 0 :(得分:0)

fetchContacts("")始终返回一个空列表,因为您没有名称为&#34;&#34;的联系人。此外,无论何时添加或插入核心数据,您都不会看到这些更改,因为您没有进行另一次提取并更新contacts数组。

您的代码的其他更常见问题:

  • 您应该将persistentContainer&#39; s viewContext视为只读。要使用perform​Background​Task(_:​)
  • 写入核心数据 创建persistentContainercontainer.viewContext.automaticallyMergesChangesFromParent = true 后,
  • 使用fetchedResultsController与您的视图同步核心数据。
  • 如果您正在对核心数据进行大量更改或插入,就像您在addContacts中所做的那样,最后进行一次保存,而不是在循环中的每次插入之后。