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
Related
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
}()
}
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
})
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.
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.
Is it really so simple now in iOS5?
I used to perform a background fetch using this code in my AppDelegate:
dispatch_queue_t downloadQueue = dispatch_queue_create("DownloadQueue", NULL);
dispatch_async(downloadQueue, ^{
self.myDownloadClass = [[MyDownloadClass alloc]initInManagedObjectContext:self.managedObjectContext];
[self.myDownloadClass download];
});
dispatch_release(downloadQueue);
My download class performs an NSURLConnection to fetch some XML data, uses NSXMLParser to parse the data, and then updates a complex schema in core data. I would always switch to the main thread to actually update the core data. Messy code, with lots of calls to dispatch_sync(dispatch_get_main_queue()....
My new code looks like this:
NSManagedObjectContext *child = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[child setParentContext:self.managedObjectContext];
[child performBlock:^{
self.myDownloadClass = [[MyDownloadClass alloc]initInManagedObjectContext:child];
[self.myDownloadClass download];
}];
along with a small change to some other code in my AppDelegate to set the parent model object context type to NSMainQueueConcurrencyType:
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
It seems to work very well. The entire update process still runs in a separate thread, but I did not have to create a thread. Seems like magic.
Just remember if you want to commit your changes to the physical core data files, you have call save: on the parent context as well.
I didn't really ask a question here. I'm posting this so it helps others because everything I found when searching for the new iOS5 managed object context methods only gave high level details with no code examples And all the other searches for fetching core data in the background are old, sometimes very old, and discuss how to do it pre-iOS5.
Yes - it is really that easy now (in iOS 5.0). For iOS 4 compatibility, the previous hurdles remain, but the documentation is not too bad on thread confinement. Maybe you should add this to a wiki section?
I'm trying to understand how this new API is implemented. My usual pattern for multithreaded core data is something like this:
Usually in a NSOperation but simplified using dispatch_async in this example:
dispatch_queue_t coredata_queue; // some static queue
dispatch_async(coredata_queue, ^() {
// get a new context for this thread, based on common persistent coordinator
NSManagedObjectContext *context = [[MyModelSingleton model] threadedContext];
// do something expensive
NSError *error = nil;
BOOL success = [context save:&error];
if (!success) {
// the usual.
}
// callback on mainthread using dispatch_get_main_queue();
});
Then the main thread will respond by updating the UI based on NSManagedObjectContextDidSaveNotification to merge the main context.
The new API's seem to be a wrapper around this pattern, where the child context looks like it just takes the persistent coordinator from its parent to create a new context. And specifying NSPrivateQueueConcurrencyType on init will make sure the performBlock parameter is executed on the private queue.
The new API doesn't seem to be much less code to type. Any advantages over the 'traditional' threading?