2017-03-18 7 views
0

コアデータを使用してアプリケーションを構築しています。それはいつも私のために今まで働いてきました。最近、 私は結果が得られません。エラーはありません。データが保持されていないようです。誰もこの奇妙な機能不全に遭遇しましたか?iOS10&Switt3 - コアデータが保存されず、結果が返されない

私の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"> 

データソースおよびセル識別子が正しく

答えて

0

fetchContacts("")接続されているあなたが「」の名前を持つ接点を持たないため、常に空のリストを返します。また、コアデータを追加または挿入するたびに、contactsアレイをフェッチして更新していないため、これらの変更が表示されません。あなたのコードで

他のより一般的な問題:

  • あなたはpersistentContainerviewContext読み取り専用として扱う必要があります。あなたがpersistentContainerを作成した後、コア・データ使用perform​Background​Task(_:​)
  • に書き込むにはcontainer.viewContext.automaticallyMergesChangesFromParent = true
  • を設定し、あなたのビューでコア・データを同期するfetchedResultsControllerを使用しています。
  • 多くの変更やコアデータへの挿入を行う場合は、addContactsをループ内に挿入した後ではなく、最後に1回保存します。
関連する問題