简体   繁体   中英

NSManagedObject and CoreData in swift 3 Xcode 8

I am using Xcode 8 and swift 3, i'm create NSManagedObject for my entity from Editor menu, NSManageObjectModel, how can use this file for fetch and create object, in Xcode 7 i'm using core data stack for creating manage object, persistent store and ,... . now I don't know how using core data in swift 3.

This bellow core data code in swift 3 working fine using x code 8 and later version and also deployment target can be low IOS 8 and later working once try it.Step wise i wrote the code .

1)import Coredata in appdelegate

          import UIKit
          import CoreData


        @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate 
              var window: UIWindow?
  1. In this code added in appdelegate only if coredata working in all version of os then you need this code

     private lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() // Core Data stack lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = Bundle.main.url(forResource: "Coredata", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSLog("Unresolved error \\(wrappedError), \\(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \\(nserror), \\(nserror.userInfo)") abort() } } } 

    3.Save the data this is what ever you need data save in to data base then you write this bellow code This write in ViewControllers class just import coredata once again and create NSManagedObject

      var dataBase = [NSManagedObject]() let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let entity = NSEntityDescription.entity(forEntityName: "YourEntityName",in:managedContext) let activityData = NSManagedObject(entity: entity!,insertInto: managedContext) activityData.setValue(storeData1, forKey: "attributeKey1") activityData.setValue(storeData2, forKey: "attributeKey2") do { try managedContext.save() dataBase.append(activityData) } catch let error as NSError { print("Could not save \\(error), \\(error.userInfo)") } } 

    4.In which class you Getting data then you write this code Here also same way just

     import coredata and create NSMangedObject var getData= [NSManagedObject]() 

    //Get Data func getLogsData() {

     let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "YourEntityName") do { let results = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch \\(error), \\(error.userInfo)") } 

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM