I am quite new to core data, which is why I am at the beginning of a learning process.
Today I tried to save Data from a SpriteKit Game in CoreData, which resulted in a bunch of errors.
Because the game template from XCode does not provide the use of core data, I had to import the Appdelegate Code (CoreData Stack) from a singleview Template. And this is where the problems begin - I guess.
I inspected the persistent store coordinator and I found:
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
First, I can not find the "SingleViewCoreData.sqlite" file in the project directory. So where is it stored? Or is it created automatically?
Second I got the "unexpectedly found nil while unwrapping an Optional value" Error. I think there might be a link to the first question?
Thanks so far. I hope you can understand my bad english.
Krusel
Related
Is it possible?
I've got a new iOS 14 app set up with Core Data and Cloudkit. I had to make a few changes to my Persistence.swift file to get it working but it's working without a hitch.
I'm interested in implementing sharing with other iCloud Users, but a lot of the documentation is out of date and confusing and it seems like it might not have been possible at one point but it is now?
I think the first step is to make my database shared? I'm adding the following line to my Persistence.swift file
container.persistentStoreDescriptions.first!.cloudKitContainerOptions?.databaseScope = .shared
(Here's the whole thing):
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "Shopmatic")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.persistentStoreDescriptions.first!.cloudKitContainerOptions?.databaseScope = .shared
}
}
but when I run the app I get the following error
Thread 1: "CKDatabaseScopeShared is not supported with NSPersistentCloudKitContainer"
Which is not encouraging, but maybe it's possible to implement sharing with a public database scope?
I'm not really sure what the next steps are? Implementing my own NSPersistentContainer that both syncs to cloudkit and allows sharing?
I believe the answer is no based on this thread on the Apple dev forums (I'm MasonAndMuse there), but there's one Apple engineer in there who was saying yes but wouldn't elaborate. I stopped trying soon after, not finding any way around the opaque nature of the system as it is now. Nothing I've seen indicates someone else has gotten it working but I haven't looked very closely after giving up 8 months ago. Of course there might be a way - I'd love to be proven wrong!
I assume they introduce sharing in iOS 15, but that's not very helpful now... Too bad because it's so close now and it will save SO much time if/when they add it in...
The Apple engineer's answer in the forum reads quite clearly to me:
NSPersistantCloudKitContainer does not support sharing!
You need to implement CloudKit sharing through CK APIs.
I have not implemented such a feature yet, but I would approach it like this:
Get the NSPersistantCloudKitContainer implementation working.
Implement CloudKit sharing on the same container.
Start passing specific records from NSPersistantCloudKitContainer into the sharing feature implemented in step 2.
To access the shared Cloudkit database with CKDatabase.Scope = shared:
If this is the NSPersistentCloudKitContainer
:
container = NSPersistentCloudKitContainer(name: "AppName")
I would try to access the shared DB of this container like so
:
let myAppsCloudKitContainer = CKContainer(identifier: "iCloud.com.name.AppName")
let myContainersSharedDatabase = myAppsCloudKitContainer.database(with: .shared)
To access data from NSPersistantCloudKitContainer for use in the CloudKit sharing feature use NSPersistantCloudKitContainer instance method
record(for managedObjectID: NSManagedObjectID)
(as of macOS 11 / Xcode 12)
I am currently working on a capacitor plugin, that should allow me to run a CoreML-model on the ios-version of my Ionic-App.
Even though I used the common terminology to access the model-file, the model is somehow not found in my ios-plugin-script. Is there a different way I can access the model besides VNCoreMLModel or is there maybe in general a problem with using CoreML models in capacitor plugins?
I also tried to load the model, using the same lines of code in a full/native swift app, what worked fine.
The model is already located in the Plugins' Directory (together with the files Plugin.swift, Plugin.m and so on...) and is accessed via calling it as //VNCoreMLModel(for: "modelname".model).
The error message in particular is : "Cannot find 'Resnet50' in scope"
code snippet:
guard let model = try? VNCoreMLModel(for: Resnet50().model) else {return}
(I personally think, that when integrating the plugin into my app, the model file is maybe not transferred into the 'Development Pods' for any reason.)
I don't know what capacitor is, but Resnet50 is a class that is automatically generated by Xcode. You either need to copy the source code for that class into your own project, or not use that class and instantiate an MLModel object for your model instead.
i have a small problem with my code. When I load data from my CoreData I get warnings in my consol but I don´t know why. I´m not a professional programmer and also google couldn´t really help me so now I´m here.
I load my data like this:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var data: [DataToLoad] = []
override func viewDidLoad(){
do{
data = try context.fetch(DataToLoad.fetchRequest())
}catch{
print("error")
}}
But when I load it like that the console says...
"2020-09-05 20:32:04.884728+0200 Test-Application[3850:348569] [general] 'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release"
...after I start the App.
So I mean everything is working fine, but where is my error that this massage appears.
I hope you can help me.
Sorry for my bad english I hope you can understand everything.
Have a nice day and thank you all.
The app is still working because it's a warning and not an error but it's good to not ignore warnings.
In your case, the warning occurs because NSKeyedUnarchiveFromData is deprecated. This means it's outdated and will be replaced in the future and the app might then stop working.
Kaira Diagne explains:
With iOS 12 Apple has started adopting NSSecureCoding across the entire platform. For Core Data this means that the default ValueTransformer, which uses NSCoding to transform a custom data type into a format that can be stored in the persistent store, at some point will change as well.
In your case NSSecureUnarchiveFromData instead of NSKeyedUnarchiveFromData in Core Data.
This means that the first thing we need to do is make sure that the data type of every transformable property in our data model conforms to secure coding.
(Link: NSSecureCoding and transformable properties in Core Data, 2020)
For your app to also work in the future you will have to dig somewhat deeper into the code and see where you are using the deprecated methods and classes and replace them.
I have a very large Project and I am right in a refactoring session. At the beginning my idea sounds good to me, but now i am stuck and confused and near before a git rollback. You guys are my last chance.
We’ve done a GUI application that shows some data that are living in CoreData. A background Process is fetching data from time to time from the network and put them into the CoreData.
So I’ve got the request thing -> pushing into CoreData and <- getting it out onto the GUI.
That works for very good for us. It’s straight forward and nothing special. My Company is programming this application since January and the requesting and data part gets huge. We also have a 100% test coverage! \o/. Working in that project could be so nice… if… if the GUI things could be separated.
As time goes by I have to split the dev-team into two parts: one for the gui (and the several gui applications that all based on the same data model) The second one for the Request-and-CoreDate part. My Model interface is clean enough to have a nice entry point, so i thought i would be easy to move the Request and CoreData sections into a library-project in my Workspace.
hm, well. no!
I put the Kit.xcdatamodeld into the new library project. I generate all models and add all the code from the main application into the lib. I resolved every problem and start to move the first basic tests into the new project.
I put the managedObjectModel part from our ApplicationDelegate into a DataController in the new project. And changed the first call to use this managedObject from the new class.
let dc = DataController()
_ = GlobalScope(context: dc.managedObjectContext!)
When I run the first test that should store a simple entity than an error occurs in managedObjectModel:
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource(" <LibName>Kit", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
fatal error: unexpectedly found nil while unwrapping an Optional value
My Question is: Is it possible to do the whole CoreData stuff into a Framework? I wan’t have any data model or requests in my gui applications? The plan ist to include the framework and use the getXY() setXY() functions of my models. Also the whole network background fetching should be places in the framework.
But it seams that there is no mainBundle in a framework. So how to get the database the right way?
Thank you very much.
ps
First, Core Data is already a framework. You are looking to put your layer on top of Core Data into a framework. Is it possible? Probably, but it is not a great idea.
There is no value in putting a third (or more) of your application into a framework. It will not make anything cleaner or easier. In fact it will make debugging of your application harder.
Separate out the code using groups in Xcode and call it there. Trying to put things into separate Xcode projects (which is what you would need) would lead to more issues than it is worth.
BTW, there is no way to compile the model into the framework as that is an independent file. Therefore your primary application would need to embed the model file anyway.
You could explore creating your own custom CocoaPod like structure but again, it really is not worth it and maintainability will decrease.
The problem is this line:
let modelURL = NSBundle.mainBundle().URLForResource(" <LibName>Kit", withExtension: "momd")!
It's looking in the main bundle for that resource, which doesn't exist. You'll want to use bundleWithIdentifier or bundleForClass instead, like:
let modelURL = NSBundle(identifier:"com.whatever.yourFrameworkIdentifier").URLForResource...
I am completely lost trying to set up core data to be used inside my nsobject class. I am adding coredata to my existing project so its quite hard to figure this all out. Because of this I have started a new project with coredata to get the sample code I need to implement coredata in my current app.. however I am wondering what alterations do I need to make in order to use this coredata sample code with an object class instead of a view controller/tableview which is what the template code is doing?
To help answer my question I will explain what I am doing with my project at the moment.
I have several viewcontrollers that display different sets of data, because I have a custom database engine I am having to communicate with I have two classes that I have made. One is a request class which creates a packet with all sorts of data that gets sent off to the DBEngine using NSURLRequest/NSURLConnection.
I am using NSURLRequest/NSURLConnection delegates in my custom request class, so when send my request off to the DBEngine i wait until I get a response inside connectionDidFinishLoading delegate method, which I then pass the response data over to my responses class like so....
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// depending on what sorta request is made will depend on how the data shuld be handled.
if ([methodName isEqualToString:#"GetDBVersion"]) {
//tbc
}
else if ([methodName isEqualToString:#"GetManuf"])
{
[engineResponses GetManuf:receivedData];
}
else if ([methodName isEqualToString:#"GetNonM"])
{
[engineResponses GetNonM:receivedData RestrictionID:RestrictionID];
}
}
By doing this I am creating a new instance of my engineResponses class, which Is okay untill I try to pass the context from the application delegate over to this same class thus creating another instance which equals to things not working....
So as stated above I am wondering how I can edit the template code to work in my favor... I hope I have been clear in my explination I have just spent the last hour on trying to get this question perfect as I have spent the last two days chasing my tail trying to figure this stuff out.. its the first time I have worked with coredata and im just finding it hard to come to grips with it because I seem to be using it in an unconventional manner....
any help would be HUGELY appreciated.. if you need any more code example or better explanations please ask.. I will do anything I can to get help..
Okay So I found out the problem was with declaring multiple instances of the same object.. So all I had to do was use a singleton design patter to get it working perfectly.
Alot of people dislike singletons but I am not sure how else to get around this issue???? any suggestions would be greatly appreciated.
Also I know this worked because I have since checked the DB by logging the storeURL in the appdelegate, then copying pasting that dir, into the goto file - then opening up the sqlite db in xcode.. all the values are in there perfectly.