How to resolve: "NSPersistentStoreCoordinator has no persistent stores"? - core-data

I'm following this tutorial exactly, which adds CoreData to an existing app:
https://www.youtube.com/watch?v=WcQkBYu86h8
When I get to the seedPerson() moc.save(), the app crashes with this error:
CoreData: error: Illegal attempt to save to a file that was never
opened. "This NSPersistentStoreCoordinator has no persistent stores
(unknown). It cannot perform a save operation.". No last error
recorded.
The NSManagedSubclass has been added.
The DataController is wired up and I can step into it. It isn't until the save() that things go wrong. Any idea what I might have left out to cause this error?

I also followed that YouTube tutorial and had the same problem. I just removed the background thread block that adds the persistent store and it worked. Here's my DataController:
import UIKit
import CoreData
class WellbetDataController: NSObject {
var managedObjectContext: NSManagedObjectContext
override init() {
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", 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(contentsOfURL: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
// let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
// let docURL = urls[urls.endIndex-1]
// /* The directory the application uses to store the Core Data store file.
// This code uses a file named "DataModel.sqlite" in the application's documents directory.
// */
// let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
// do {
// try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
// } catch {
// fatalError("Error migrating store: \(error)")
// }
// }
}
}

Unfortunately, that video uses some code from Apple's website, and that code example is flawed. The main flaw is that it caches the MOC before the persistent store has been added to the MOC. Thus, if the creation of the store fails at all, the managed object context will be initialized with a persistent store coordinator that has no store.
You need use the debugger and step through the code that creates the PSC (the DataController.init method) and see why the failure happens. If you cut/paste the same way as in that example, then maybe you also forgot to change the name of your model when instantiating the model.
In any event, the most likely cause is that some initialization code in that function failed, and you are subsequently going happily along with a core data stack that has no stores.

You need to load the persistent stores
let persistentContainer = NSPersistentContainer(name: "DbName")
persistentContainer.loadPersistentStores() { [weak self] _, error in
self?.persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
}

The problem is on these two lines:
guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else {
&&
let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
DataModel needs to be changed to the name of your application if your CoreData was created automatically by Xcode. Look for these lines in AppDelegate.swift

If this is the first time that you run the application after you put the core data in it then maybe it could work by removing the app from simulator and run it again.
It was happened to me and it works after I did that.

Related

Core data + CloudKit - sharing between iOS and watchOS companion app

In my app I store data with core data.
Recently I discovered the new feature introduced by Apple in WWDC19 which allows core data to work with CloudKit.
I just enabled cloudKit for my app and used an NSPersistentCloudKitContainer instead of NSPersistentContainer and all was set up ! All my data is shared between ios devices.
That works like NSPersistentContainer but it sends a copy of changes on icloud server, so there is always a local cache of data.
Now I'd like to access that data from my apple watch companion app but not all the data, only a specific entity!
So how could I do that?
I tried to set the NSPersistentCloudKitContainer shared between both targets with the attribut inspector but watch don't get any data. I can see in cloudKit dashboard there are requests from watchOS but watch just don't get any data.
But if I save an entity from the watch to core data I can get it only from the watch.
My conclusion is both are no storing the data at the same place. So how could I fix that? There are already using the same NSPersistendCloudKitContainer.
the container shared between both targets :
import Foundation
import CoreData
public class CoreDataContainer {
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 = NSPersistentCloudKitContainer(name: "MyProjectName")
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)")
}
}
}
}
Resolved by adding a cloudKitContainerOptions to my context description like this :
class CoreDataStack {
static let persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "MyProjectName")
let description = container.persistentStoreDescriptions.first
description?.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "myCloudContainerID") // HERE !
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
}

managedObjectContext in Swift 3

I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot properly replace the line
// set up the NSManagedObjectContext
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
managedContext = appDelegate.managedObjectContext
even though I found this related question (which however is iOS not OS X). How can I replace that piece of code which produces the error message Value of type 'AppDelegate' has no member 'managedContext'?
Swift 3 in macOS
let appDelegate = NSApplication.shared().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
The error you provided says 'AppDelegate' has no member 'managedContext' instead of 'AppDelegate' has no member 'managedObjectContext', which would lead me to assume you just need to fix your syntax.
Swift 3 in iOS 10
Core Data needs at least 3 things to work:
A managed object model
A persistent store coordinator
And a managed object context
Put those three things together and you get the Core Data Stack.
When iOS 10 came out, a new object was introduced called the NSPersistentContainer which encapsulates the core data stack.
How to create the container object is answered here.
managedObjectContext is now a property called viewContext, accessed via:
let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext
A helpful article is What's New in Core Data, but if that reading seems a little too heavy, this WWDC video does a great job of explaining this topic.
AppDelegate has below members only
// 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: "")
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
}()
so use
let managedContext = (UIApplication.shared.delegate as! appDelegate).persistentContainer.viewContext
This will work fine
For macOS and Swift 3.1
let moc: NSManagedObjectContext = (NSApplication.shared().delegate as! AppDelegate).persistentContainer.viewContext
I swift 3 you can get managedContext set by this code:
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

Redis Connections May Not be Closing with c#

I'm connecting to Azure Redis and they show me the number of open connections to my redis server. I've got the following c# code that encloses all my Redis sets and gets. Should this be leaking connections?
using (var connectionMultiplexer = ConnectionMultiplexer.Connect(connectionString))
{
lock (Locker)
{
redis = connectionMultiplexer.GetDatabase();
}
var o = CacheSerializer.Deserialize<T>(redis.StringGet(cacheKeyName));
if (o != null)
{
return o;
}
lock (Locker)
{
// get lock but release if it takes more than 60 seconds to complete to avoid deadlock if this app crashes before release
//using (redis.AcquireLock(cacheKeyName + "-lock", TimeSpan.FromSeconds(60)))
var lockKey = cacheKeyName + "-lock";
if (redis.LockTake(lockKey, Environment.MachineName, TimeSpan.FromSeconds(10)))
{
try
{
o = CacheSerializer.Deserialize<T>(redis.StringGet(cacheKeyName));
if (o == null)
{
o = func();
redis.StringSet(cacheKeyName, CacheSerializer.Serialize(o),
TimeSpan.FromSeconds(cacheTimeOutSeconds));
}
redis.LockRelease(lockKey, Environment.MachineName);
return o;
}
finally
{
redis.LockRelease(lockKey, Environment.MachineName);
}
}
return o;
}
}
}
You can keep connectionMultiplexer in a static variable and not create it for every get/set. That will keep one connection to Redis always opening and proceed your operations faster.
Update:
Please, have a look at StackExchange.Redis basic usage:
https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md
"Note that ConnectionMultiplexer implements IDisposable and can be disposed when no longer required, but I am deliberately not showing using statement usage, because it is exceptionally rare that you would want to use a ConnectionMultiplexer briefly, as the idea is to re-use this object."
It works nice for me, keeping single connection to Azure Redis (sometimes, create 2 connections, but this by design). Hope it will help you.
I was suggesting try using Close (or CloseAsync) method explicitly. In a test setting you may be using different connections for different test cases and not want to share a single multiplexer. A search for public code using Redis client shows a pattern of Close followed by Dispose calls.
Noting in the XML method documentation of Redis client that close method is described as doing more:
//
// Summary:
// Close all connections and release all resources associated with this object
//
// Parameters:
// allowCommandsToComplete:
// Whether to allow all in-queue commands to complete first.
public void Close(bool allowCommandsToComplete = true);
//
// Summary:
// Close all connections and release all resources associated with this object
//
// Parameters:
// allowCommandsToComplete:
// Whether to allow all in-queue commands to complete first.
[AsyncStateMachine(typeof(<CloseAsync>d__183))]
public Task CloseAsync(bool allowCommandsToComplete = true);
...
//
// Summary:
// Release all resources associated with this object
public void Dispose();
And then I looked up the code for the client, found it here:
https://github.com/StackExchange/StackExchange.Redis/blob/master/src/StackExchange.Redis/ConnectionMultiplexer.cs
And we can see Dispose method calling Close (not the usual override-able protected Dispose(bool)), further more with the wait for connections to close set to true. It appears to be an atypical dispose pattern implementation in that by trying all the closure and waiting on them it is chancing to run into exception while Dispose method contract is supposed to never throw one.

Threading + multiple windows causing strange errors

I have 2 windows in swift, one is like a login dialog which sends an NSURLConnection.sendAsynchronousRequest to a server to get authenticated. Once it gets the response, the window is supposed to close.
When I close the Window (either from the login window class or main window clasS) I get these errors:
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
I have tried all manner of background threads etc. But I think the issue is that I am closing the window why the asynch NSURLConnection request is still hanging.
My code to send the async request from the login window:
dispatch_async(dispatch_get_main_queue(), {
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
let result: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
let expectedString = "special auth string"!
if(result == expectedString) {
self.callback.loginOK()
} else {
self.output.stringValue = result
}
return
})
})
The callback member of the class is the parent view contoller that spawns it, I then close the login window using loginVC.view.window?.close() from the main application window. That causes the error.
The problem is that NSURLConnection.sendAsynchronousRequest will always run in a secondary thread and thus its callback will be called from that secondary thread despite you calling it explicitly from main thread.
You don't need to wrap NSURLConnection.sendAsynchronousRequest in the main thread, instead wrap your ' self.callback.loginOK()' to run in main thread using the dispatch_async to ensure no UI related operations take place in secondary thread. Something like this-
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
let result: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
dispatch_async(dispatch_get_main_queue() {
let expectedString = "special auth string"!
if(result == expectedString) {
self.callback.loginOK()
} else {
self.output.stringValue = result
}
})
return
})

Is it safe to pass NSManagedObject(created in main context) from a background thread to the main thread?

I am using AFNetworking to parse some data and then save to CoreData, I want to do something like this.
let parserContext: NSManagedObjectContext = MTCoreDataManager.sharedManager().newPrivateManagedObjectContext()
let mainContext: NSManagedObjectContext = MTCoreDataManager.sharedManager().managedObjectContext()
override func responseObjectForResponse(response: NSURLResponse!, data: NSData!, error: NSErrorPointer) -> AnyObject? {
var model: NSManagedObject?
parserContext.performBlockAndWait {
....parsing data...
....create model and assign value...
....save model...
let objID = model.objectID
mainContext.performBlockAndWait {
model = mainContext.objectWithID(objID)
}
}
return model
}
let op = AF.GET(path, parameters: nil, success: { (operation: AFHTTPRequestOperation, response: AnyObject) -> Void in
// main thread
println(response)
}) { (operation: AFHTTPRequestOperation, error: NSError) -> Void in
println(error.description)
}
As responseObjectForResponse runs in a background thread, I want to use a background context to parse the data and create the NSManagedObject in that context, and then get back the object in main thread as the final callback will be on the main thread, I don't want to return the NSManagedObjectID, I want to return the NSManagedObject but I don't know if this is safe.
Is it safe? I don't think it is.
Instead you should create a child context in the completion block and do all your Core Data saving within a block.
childContext.performBlockAndWait() {
// parse, insert and save
}
Remember that saving will just "push" the changes up to the main context. You will still have to save them to the persistent store. The main context should be aware of any changes automatically (via a NSFetchedResultsControllerDelegate or NSNotificationCenter).
I have an additional convenience method in my data manager class (or app delegate) to save the data to the persistent store, similar to the plain vanilla saveContext method provided by the Apple templates. This should a method that can be called safely from anywhere by also using above block API to save the context.

Resources