tl;dr:
clone the project: https://github.com/Jasperav/CoreDataInMemoryFail
Run the test and see it fail. Why does my in memory container not have any data and how can I make sure it will have data?
Long:
I have a sqlite file with filled data and I have an in-memory database in CoreData. Some code:
// ...
func createInMemoryPerformanceTestDatabase() -> NSPersistentContainer {
let url = createPathToSomeSQLiteFile()
let container = NSPersistentContainer(name: dataModelName, managedObjectModel: objectModel)
let description = NSPersistentStoreDescription(url: url)
description.type = NSInMemoryStoreType
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { description, error in
XCTAssertNil(error)
}
return container
}
// ...
Although the sqlite file has data inside it, I don't see it back inside my contexts I create with container.
When I create an in-memory database with CoreData pointing to a sqlite file with data, I don't see any results when querying the database. I want to see the data inside the sqlite file. The data should just load all in memory. This is for testing purposes.
The problem with what you have tried was that you set the type of your storeDescription as NSInMemoryStoreType before loading them into the container. Since, the type of storeDescription is stated as NSInMemoryStoreType the api won't read and populate data from the file URL you have provided. In order for the api to read the data from the file url, the type of storeDescription must be the one defined by initialising with the initialiser init(url: URL) which is SQLite in your case.
However if you want to have a persistentStore of type NSInMemoryStoreType with data read from the file url, you can migrate the persistentStores of your persistentContainer with NSInMemoryStoreType type using function migratePersistentStore:toURL:options:withType:error:. You can try out the code snippet below.
import CoreData
import XCTest
#testable import CoreDataInMemoryFail
class CoreDataInMemoryFailTests: XCTestCase {
private func createContainer(modify: (NSPersistentContainer) -> ()) -> NSPersistentContainer {
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: "InMemoryDatabase", ofType: "sqlite")!
let url = URL(fileURLWithPath: path)
let persistentContainer = createPersistentContainer(dataModelName: "InMemoryDatabase")
let storeDescription = NSPersistentStoreDescription(url: url)
persistentContainer.persistentStoreDescriptions = [storeDescription]
persistentContainer.loadPersistentStores { description, error in
XCTAssertEqual(storeDescription.type, description.type)
XCTAssertNil(error)
}
modify(persistentContainer)
return persistentContainer
}
func testFail() {
let persistentContainer = createContainer(modify: { _ in })
let inMemoryContainer = createContainer { persistentContainer in
let coordinator = persistentContainer.persistentStoreCoordinator
coordinator.persistentStores.forEach { (persistentStore) in
do {
try coordinator.migratePersistentStore(persistentStore, to: NSPersistentContainer.defaultDirectoryURL(), options: nil, withType: NSInMemoryStoreType)
} catch {
print("Error while migrating persistentStore")
}
}
}
let persistentContainerCoordinator = persistentContainer.persistentStoreCoordinator
persistentContainerCoordinator.persistentStores.forEach { (persistentStore) in
XCTAssertEqual(persistentStore.type, "SQLite")
}
let inMemoryContainerCoordinator = inMemoryContainer.persistentStoreCoordinator
inMemoryContainerCoordinator.persistentStores.forEach { (persistentStore) in
XCTAssertEqual(persistentStore.type, NSInMemoryStoreType)
}
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
let persistentContainerCount = (try! persistentContainer.viewContext.fetch(fetchRequest)).count
let inMemoryContainerCount = (try! inMemoryContainer.viewContext.fetch(fetchRequest)).count
XCTAssertEqual(8, persistentContainerCount)
XCTAssertEqual(persistentContainerCount, inMemoryContainerCount)
}
}
In the above snippet, I have also added asserts to verify whether persistentStore type is NSInMemoryStoreType in your inMemoryContainer and SQLite in your persistentContainer. Hope it helps.
The InMemoryType is not loading the date from your url as the other answer suggests. If you need to load the data from the file then please use the Migrate approach mentioned however if you only need to fill it with random data for testing purposes then here is another solution.
import CoreData
import XCTest
#testable import CoreDataInMemoryFail
class CoreDataInMemoryFailTests: XCTestCase {
var persistentContainer: NSPersistentContainer!
var inMemoryContainer: NSPersistentContainer!
override func setUp() {
super.setUp()
persistentContainer = createContainer(modify: { _ in })
inMemoryContainer = createContainer { storeDescription in
storeDescription.type = NSInMemoryStoreType
}
initStubs()
}
override class func tearDown() {
super.tearDown()
}
private func createContainer(modify: (NSPersistentStoreDescription) -> ()) -> NSPersistentContainer {
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: "InMemoryDatabase", ofType: "sqlite")!
let url = URL(fileURLWithPath: path)
let fileManager = FileManager.default
let uuid = UUID().uuidString
let saveDirectory = fileManager
.urls(for: .cachesDirectory, in: .userDomainMask)[0]
.appendingPathComponent(uuid)
let saveLocation = saveDirectory.appendingPathComponent(url.lastPathComponent)
try! fileManager.createDirectory(at: saveDirectory, withIntermediateDirectories: false)
try! fileManager.copyItem(at: url, to: saveLocation)
let persistentContainer = createPersistentContainer(dataModelName: "InMemoryDatabase")
let storeDescription = NSPersistentStoreDescription(url: saveLocation)
modify(storeDescription)
print("TYPE OF STORE IS: \(storeDescription)")
persistentContainer.persistentStoreDescriptions = [storeDescription]
persistentContainer.loadPersistentStores { description, error in
XCTAssertEqual(storeDescription.type, description.type)
XCTAssertNil(error)
}
return persistentContainer
}
func initStubs() {
func inserPerson( age: Int32) -> Person? {
let obj = NSEntityDescription.insertNewObject(forEntityName: "Person", into: inMemoryContainer.viewContext)
obj.setValue(age, forKey: "age")
return obj as? Person
}
_ = inserPerson(age: 1)
_ = inserPerson(age: 2)
_ = inserPerson(age: 3)
_ = inserPerson(age: 4)
_ = inserPerson(age: 5)
do {
try inMemoryContainer.viewContext.save()
} catch {
print("create fakes error \(error)")
}
}
func removeData() {
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let objs = try! inMemoryContainer.viewContext.fetch(fetchRequest)
for case let obj as NSManagedObject in objs {
inMemoryContainer.viewContext.delete(obj)
}
try! inMemoryContainer.viewContext.save()
}
func testFail() {
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
let persistentContainerCount = (try! persistentContainer.viewContext.fetch(fetchRequest)).count
let inMemoryContainerCount = (try! inMemoryContainer.viewContext.fetch(fetchRequest)).count
XCTAssertEqual(8, persistentContainerCount)
XCTAssertEqual(5, inMemoryContainerCount)
}
}
More info can be found here
Related
In my swift code below the goal is to save a uiimage using pngdata into core data. The problem is right now it does not appear to be saving because "test numbers" is not being printed into the debug section. I don't know how to make sure its being save. I am looking to save the image and verify its there.
override func viewDidLoad() {
super.viewDidLoad()
let gwen = UIImage(named: "f.jpeg")
if let imageData = gwen.self?.pngData() {
DataBaseHelper.shareInstance.saveImage(data: imageData)
}
let arr = DataBaseHelper.shareInstance.fetchImage()
print("test number : ",arr)
}
Other Class
class DataBaseHelper {
static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func saveImage(data: Data) {
let imageInstance = Info(context: context)
imageInstance.img = data
do {
try context.save()
print("Image is saved")
} catch {
print(error.localizedDescription)
}
}
func fetchImage() -> [Info] {
var fetchingImage = [Info]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Info")
do {
fetchingImage = try context.fetch(fetchRequest) as! [Info]
} catch {
print("Error while fetching the image")
}
return fetchingImage
}
}
It is a bad approach to saving image in core data!
For saving heavy documents iOS provides you document directory folder which is fast and efficient to save and retrieve than core data and user defaults.
Core data is an sqlite table which is just light weight properties like strings, numbers and Date etc.
Here is a trick you just save your image in document directory folder of your application which has large space and save the reference/ filename into core data.
Rather than creating data property you should have to create imageName property
import Foundation
import CoreData
extension Info {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Info> {
return NSFetchRequest<Info>(entityName: "Info")
}
#NSManaged public var imageName: String?
}
extension Info : Identifiable {
}
After that add this extension for save and get image from document folder
extension UIImage {
func save(to fileName:String) {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
let fileURL = documentsUrl.appendingPathComponent(fileName)
if let imageData = self.jpegData(compressionQuality: 1) {
try? imageData.write(to: fileURL, options: .atomic)
}
}
convenience init(fileName: String) {
var data = Data()
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
let fileURL = documentsUrl.appendingPathComponent(fileName)
do {
let imageData = try Data(contentsOf: fileURL)
data = imageData
} catch {
print(error.localizedDescription)
}
self.init(data: data)!
}
}
then how you can save and retrieve reference in core data and image document folder.
class ViewVC:UIViewController {
var images:[UIImage] = [] {
didSet {
print(images.count)
// reload tableView or collectionView
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func saveImage(image:UIImage,fileName:String) {
image.save(to: fileName)
DataBaseHelper.shareInstance.saveImage(fileName: fileName)
}
func getImage() {
let allInfo = DataBaseHelper.shareInstance.fetchInfo()
for info in allInfo {
if let name = info.imageName {
let image = UIImage(fileName: name)
self.images.append(image)
}
}
}
}
you helper class
class DataBaseHelper {
static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func saveImage(fileName: String) {
let imageInstance = Info(context: context)
imageInstance.imageName = fileName
do {
try context.save()
print("Image name is saved")
} catch {
print(error.localizedDescription)
}
}
func fetchInfo() -> [Info] {
var fetchingImage = [Info]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Info")
do {
fetchingImage = try context.fetch(fetchRequest) as! [Info]
} catch {
print("Error while fetching the image")
}
return fetchingImage
}
}
I am attempting to migrate an app from Swift to SwiftUI but am struggling with Core Data. I run both the Swift and SwiftUI apps under the same bundle identifier so they are accessing the same underlying data but although I use the same xcdatamodeld model name for both, they both point to different data bases.
What I need to do is run the app on Swift and load data into Core Data. Then re-run the SwiftUI version of the app and be able to load the identical data.
Here the code for the Swift version:
class DataStore {
static let sharedDataStore = DataStore()
var managedContext: NSManagedObjectContext!
lazy var coreDataStack = CoreDataStack()
fileprivate init() {
self.managedContext = coreDataStack.context
}
func createParcours() -> Parcours {
let parcours = Parcours(context: managedContext)
parcours.timeStamp = NSDate()
return parcours
}
func deleteParcours(_ toDelete: Parcours) {
managedContext.delete(toDelete)
self.saveParcours()
}
func saveContext(parcours: Parcours?) {
if let parcours = parcours {
encodeParcours(parcours)
}
coreDataStack.saveContext()
}
}
class CoreDataStack {
let modelName = "MyParcours" // Exactly same name as name.xcdatamodeld
fileprivate lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var context: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.psc
return managedObjectContext
}()
fileprivate lazy var psc: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent(self.modelName)
do {
let options = [NSMigratePersistentStoresAutomaticallyOption: true]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
fileprivate lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: self.modelName, withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
func saveContext () {
guard context.hasChanges else {return}
do {
try context.save()
} catch let error as NSError {
print("Unresolved error: \(error), \(error.userInfo)")
}
}
}
And in the SwiftUI version, I generate the NSPersistentContainer() and inject it into the ContentView:
class DataController: ObservableObject {
let container = NSPersistentContainer(name: "MyParcours")
init() {
container.loadPersistentStores { NSEntityDescription, error in
if let error = error {
print("Core Data failed to load: \(error.localizedDescription)")
}
}
}
}
#main
struct MySwiftUIApp: App {
#StateObject private var dataController = DataController()
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, dataController.container.viewContext)
}
}
}
Any pointers where I am going wrong?
I found out why the database did not show up in the SwiftUI version of the app. The reason is that Apple changed the storage location in some earlier version of iOS (not certain exactly when), originally located in the Documents folder and now in the Library/Application%20Support.
So the solution is to change the url of the NSPersistentStoreDescription:
init() {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0].appendingPathComponent("MyParcours")
self.container = NSPersistentContainer(name: "MyParcours")
// Change URL to allow for compatibility with older version in Swift
let description = NSPersistentStoreDescription(url: documentsDirectory)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { NSEntityDescription, error in
etc.
I just added App Groups to my app using this StackOverFlow post. Unfortunately since the defaultDirectoryURL is changing, I can not fetch any of the old data I made before using the App Groups directory. I know the data is still there because when I switch back to using a regular NSPersistentContainer instead of the GroupedPersistentContainer, I can get the data.
How can I migrate my old data over to where I'm fetching the app group's data?
Core Data code:
class CoreDataManager {
static let sharedManager = CoreDataManager()
private init() {}
lazy var persistentContainer: NSPersistentContainer = {
var useCloudSync = UserDefaults.standard.bool(forKey: "useCloudSync")
let containerToUse: NSPersistentContainer?
if useCloudSync {
containerToUse = NSPersistentCloudKitContainer(name: "App")
} else {
containerToUse = GroupedPersistentContainer(name: "App")
let description = containerToUse!.persistentStoreDescriptions.first
description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
}
guard let container = containerToUse, let description = container.persistentStoreDescriptions.first else {
fatalError("Hey Listen! ###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
...
return container
}
}
GroupedPersistentContainer code:
class GroupedPersistentContainer: NSPersistentContainer {
enum URLStrings: String {
case group = "group.App"
}
override class func defaultDirectoryURL() -> URL {
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: URLStrings.group.rawValue)
if !FileManager.default.fileExists(atPath: url!.path) {
try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
}
return url!
}
}
I haven't done this yet for my NSPersistentCloudKitContainer yet but it will follow the same format as this one.
I would like to test my core data methode.
There is multiples entities in my coredataModel and for each I have a NSManagedObject class
there is methode inside those classes to add, delete and remove data of the corresponding entity.
public class StoredGame: NSManagedObject {
static private let storage = DataManager.shared.storage
static var all: [Game] {
let request: NSFetchRequest<StoredGame> = StoredGame.fetchRequest()
guard let storedGame = try? storage.viewContext.fetch(request) else { return [] }
var games: [Game] = .init()
storedGame.forEach { (storedGame) in
games.append(convert(storedGame))
}
return games
}
static func add(new game: Game) {
let entity = NSEntityDescription.entity(forEntityName: "StoredGame", in: storage.viewContext)!
let newGame = StoredGame(entity: entity, insertInto: storage.viewContext)
try? storage.saveContext()
}
}
and then I have a class responsible of the core data stack
class CoreDataManager {
private lazy var persistentContainer: NSPersistentContainer! = {
guard let modelURL = Bundle.main.url(forResource: "CoreData", withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let container = NSPersistentContainer(name: "CoreData", managedObjectModel: mom)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
var viewContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
func saveContext () throws {
let context = viewContext
if context.hasChanges {
do {
try context.save()
} catch(let error) {
print(error)
}
}
}
}
Then when it goes to the tests. I've created a mockContainer and a mockCoreData
lazy var mockContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CoreData")
container.persistentStoreDescriptions[0].url = URL(fileURLWithPath: "/dev/null")
container.loadPersistentStores(completionHandler: { (_, error) in
XCTAssertNil(error)
})
return container
}()
lazy var mockCoreData = {
return StoredGame(context: mockContainer.viewContext)
}()
So now I dont know how to run tests in that configuration, I've tried a
XCTAssert(StoredGame.all.isEmpty) for exemple ( i have a all var in the StoredEntity class)
but it fails with an error telling
'NSInvalidArgumentException', reason: '-[CoreData.StoredEntity setId:]: unrecognized selector sent to instance
any idea?
This might be occurring with passing an invalid URL for the store description. Unless you need to run tests with a NSSQLiteStoreType, which is the default for NSPersistentContainer, you may want to consider using an NSInMemoryStoreType for unit testing. A small tweak to your CoreDataManager class could allow you to initialize the class both for your app and unit tests. For example:
class CoreDataManager {
private let persisted: Bool
init(persisted: Bool = true) {
self.persisted = persisted
}
lazy var persistentContainer: NSPersistentContainer = {
let description = NSPersistentStoreDescription()
if persisted {
description.type = NSSQLiteStoreType
description.url = // location to store the db.
} else {
description.type = NSInMemoryStoreType
}
let container = NSPersistentContainer(name: "CoreData")
container.persistentStoreDescriptions = [description]
container.loadPersistentStores //...
return container
}()
}
Then you can use this exact class in your unit tests without need to create a mock. Just initialize it without persistence:
let manager = CoreDataManager(persisted: false)
I'm currently learning Core Data and I have two view controllers that are using the same piece of code to get a users profile. The problem is that it's the same code copy and pasted and I would like to avoid this. I'm using the Managed Class approach to access the data and each controller has the following method:
var profileHolder: Profile!
let profileRequest = Profile.createFetchRequest()
profileRequest.predicate = NSPredicate(format: "id == %d", 1)
profileRequest.fetchLimit = 1
if let profiles = try? context.fetch(profileRequest) {
if profiles.count > 0 {
profileHolder = profiles[0]
}
}
if profileHolder == nil {
let newProfile = Profile(context: context)
newProfile.id = 1
newProfile.attempts = nil
profileHolder = newProfile
}
profile = profileHolder
Profile is a var inside the controller: var profile: Profile! and I call the above inside viewWillAppear()
I know there's a cleaner approach and I would like to move this logic inside the class but unsure how to.
Thanks
var profileHolder: Profile!
profileHolder here is force unwrapping optional value. And you are fetching from core data and assigning the value in viewWillAppear, which is risky as profileHolder would be nil and can trigger crash if you access it before viewWillAppear.
My suggestion would be:
var profileHolder: Profile
{
if let profiles = try? context.fetch(profileRequest),
profiles.count > 0
{
return profiles[0]
}
else
{
let newProfile = Profile(context: context)
newProfile.id = 1
newProfile.attempts = nil
return newProfile
}
}()
This will ensure profileHolder is either fetched or created when the view controller is initialised.
However this would not work if
context
is a stored property of viewController, in which case, do:
var profileHolder: Profile?
override func viewDidLoad()
{
if let profiles = try? context.fetch(profileRequest),
profiles.count > 0
{
return profiles[0]
}
else
{
let newProfile = Profile(context: context)
newProfile.id = 1
newProfile.attempts = nil
return newProfile
}
}
Here is the struct I created for a project I did that allows me to access my CoreData functions anywhere. Create a new empty swift file and do something like this.
import CoreData
// MARK: - CoreDataStack
struct CoreDataStack {
// MARK: Properties
private let model: NSManagedObjectModel
internal let coordinator: NSPersistentStoreCoordinator
private let modelURL: URL
internal let dbURL: URL
let context: NSManagedObjectContext
let privateContext: NSManagedObjectContext
// MARK: Initializers
init?(modelName: String) {
// Assumes the model is in the main bundle
guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd") else {
print("Unable to find \(modelName)in the main bundle")
return nil
}
self.modelURL = modelURL
// Try to create the model from the URL
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
print("unable to create a model from \(modelURL)")
return nil
}
self.model = model
// Create the store coordinator
coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
// create a context and add connect it to the coordinator
//context.persistentStoreCoordinator = coordinator
privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = coordinator
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.parent = privateContext
// Add a SQLite store located in the documents folder
let fm = FileManager.default
guard let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Unable to reach the documents folder")
return nil
}
self.dbURL = docUrl.appendingPathComponent("model.sqlite")
// Options for migration
let options = [NSInferMappingModelAutomaticallyOption: true,NSMigratePersistentStoresAutomaticallyOption: true]
do {
try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: options as [NSObject : AnyObject]?)
} catch {
print("unable to add store at \(dbURL)")
}
}
// MARK: Utils
func addStoreCoordinator(_ storeType: String, configuration: String?, storeURL: URL, options : [NSObject:AnyObject]?) throws {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: nil)
}
}
// MARK: - CoreDataStack (Removing Data)
internal extension CoreDataStack {
func dropAllData() throws {
// delete all the objects in the db. This won't delete the files, it will
// just leave empty tables.
try coordinator.destroyPersistentStore(at: dbURL, ofType:NSSQLiteStoreType , options: nil)
try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: nil)
}
}
// MARK: - CoreDataStack (Save Data)
extension CoreDataStack {
func saveContext() throws {
/*if context.hasChanges {
try context.save()
}*/
if privateContext.hasChanges {
try privateContext.save()
}
}
func autoSave(_ delayInSeconds : Int) {
if delayInSeconds > 0 {
do {
try saveContext()
print("Autosaving")
} catch {
print("Error while autosaving")
}
let delayInNanoSeconds = UInt64(delayInSeconds) * NSEC_PER_SEC
let time = DispatchTime.now() + Double(Int64(delayInNanoSeconds)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.autoSave(delayInSeconds)
}
}
}
}
Create a class(CoreDataManager) that can manage core data operations.
import CoreData
class CoreDataManager:NSObject{
/// Application Document directory
lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
/// Core data manager
static var shared = CoreDataManager()
/// Managed Object Model
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: “your DB name”, withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
/// Persistent Store Coordinator
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."
let options = [ NSInferMappingModelAutomaticallyOption : true,
NSMigratePersistentStoresAutomaticallyOption : true]
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
persistanceStoreKeeper.sharedInstance.persistanceStorePath = url
} 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)
abort()
}
return coordinator
}()
/// Managed Object Context
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
/// Save context
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
Add the bellow function in your class.
func fetchProfile(profileId:String,fetchlimit:Int,completion: ((_ fetchedList:["Your model class"]) -> Void)){
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Your entity name")
let predicate:NSPredicate = NSPredicate(format: "id = %#", profileId)
fetchRequest.predicate=predicate
fetchRequest.fetchLimit = fetchlimit
do {
let results =
try CoreDataManager.shared.managedObjectContext.fetch(fetchRequest)
let profileList:["Your model class"] = results as! ["Your model class"]
if(profileList.count == 0){
//Empty fetch list
}
else{
completion(profileList)
}
}
catch{
//error
}
}
replace "Your model class" according to your requirement.
You can call the function "fetchProfile" and you will get the result inside the completion block.