Deleting CoreData store on OS X? - xcode

I'm playing around with CoreData in a Mac OS X application. After changing an entity i got the following error:
The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store.
All answers i've found for this issue suggest implementing versioning/migration into the app, but I'm not interested in saving my data. Isn't there a less complicated solution for that? Like deleting the stock file or something like that? And if yes, where is this file located?
Thanks.

If you don't want the data, then yes, you can simply delete the old file and create a new one. If your data is document based, then the document itself should be deleted. If you use a single store for the whole application (not document based), then you should look in the code that creates the store object to find the location. The template places the creation code in the application delegate, and the default location for the store is in ${HOME}/Library/Application Support/${APP_NAME}/.

On OS X 10.7 Lion when the app is sandboxed, it is stored in:
~/Library/Containers/com.yourcompany.yourAppName/

I found that for Mac OS X 10.8 / Xcode 4.6 the data is stored in the derived data folder of under
Users/*username*/Library/Developer/Xcode/DerivedData/*app name*-*random string*/Build/Products/Debug/*app name*.sqlite
The easiest way to delete this data is to go to the organiser, select project tab and click "Delete..." button by derived data.

Alternatively, For OSX, use the Nsfilemanager to delete the file by using the url defined in the lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator{...}
In this var persistentStoreCoordinator a url will be defined that is designed to be used by the persistentStoreCoordinator. You can just use the url defined there to delete the old store. Insert the below code. Run the project and the file will be deleted. Then delete the code to allow objects to be stored again and not delete the data every time.
here is what I found in the lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CocoaAppCD.storedata")
here is what i put immediately underneath it.
do{
try NSFileManager.defaultManager().removeItemAtURL(url)
} catch{
print("could not delete file")
}
then i clicked run. It ran once then i delete the code i just made so that the data would not be deleted every time

In macOS Big Sur (11.4), local NSPersistentCloudKitContainer Core Data storage can be found at:
~/Library/Containers/yourAppName/Data/CloudKit/

On Mac OS X 10.11.4 with Xcode 7.3 cleaning the fixed the problem for me:
Product > Clean or Shift⌘K

Try to run the app in a simulator of another device that you haven't used before and see if it helps you (i.e. iPhone SE instead of iPhone 7). If it does, then removing the corrupted folders should help. Open Terminal and run the following commands:
sudo rm -rf ~/Library/Developer/CoreSimulator/Devices
to remove the simulators' data that might be corrupted,
sudo rm -rf ~/Library/Developer/XCode/DerivedData/
to remove your app's data.
Hope that helps!

Related

Prevent or clear app state persistence for MacOS SwiftUI Document Based App

I am developing a MacOS Document based app using SwitfUI on MacOS 12.0.1 using Xcode 13.1 on a MacbookPro M1 Pro. I am encountering an issue that the app is always re-opening the document browser at the last used directory. Which is OK when it is on the Machine but a pain if the last used was on a network drive. I am trying to find a way of suppressing this "always restore using the last directory" mode of operation.
I have tried using the #NSApplicationDelegateAdaptor approach and implementing;
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
print(#function + " returning false")
return false
}
within my NSApplicationDelegate class, which does get called (although it seems sometimes after the dialog is presented), however this does not stop the app secretly remembering the last directory.
Does any know where this information might be being hidden or if it can be suppressed ?
I have looked for, but cannot find, a way of injecting a starting directory into a DocumentGroup as a possible solution.
TIA Alan.
Ok, for anyone who ends up here looking for a similar issue.
After a chunk of digging I found the answer, for me, was to add
UserDefaults.standard.removeObject(forKey: "NSNavLastRootDirectory")
into the app startup. It was also suggested to do
UserDefaults.standard.removeObject(forKey: "NSNavLastCurrentDirectory")
However, just doing the first appears to suppress the file open dialog, doing both causes the file open dialog to open with the user Documents directory.

Where is my database located of my MacOS app?

What is the database location of a MacOS application when using Core Data ?
I searched everywhere on my Mac and did't find it.
I Have the hidden files OFF and I'm sure there is data in my database.
Also I don't use app Sandbox.
If you have sandboxing enabled for your app, it will be placed under ~/Library/Containers/app.bundle.id/Data/Library/Application Support/AppTargetName where app.bundle.id is the Bundle Identifier specified in your app's target and AppTargetName is the name of that target, i.e. the name of the generated .app file. In that folder you should find the SQLite files that contain the database data.
Look for the persistentStoreCoordinator method in your AppDelegate.m. There is a line
NSURL *applicationDocumentsDirectory = [self applicationDocumentsDirectory];
Just add
NSLog(#"myDirectory: %#", applicationDocumentsDirectory);
This assumes you started your project with Xcode 8 Cocoa template with "use Core Data" option.
Or add
NSLog(#"Array of CD stores: %#", self.persistentStoreCoordinator.persistentStores);
to applicationDidFinishLaunching, for example. The resulting path should be in your user's library Users/<user>/Library/Application Support/<whatever>/<appname>.storedata.
Ask your NSPersistentStoreCoordinator.

reason = "The model used to open the store is incompatible with the one used to create the store"

i am creating os x app with core data. when i am modify the model. the error occurred that is showed in the image. the reason shown is "The model used to open the store is incompatible with the one used to create the store"; how to fix this error. this same error i fixed by clearing the simulator in iOS app . how to fix this in os x app.
enter image description here
If you look at the code that sets up your persistentStoreCoordinator, it should tell you where the storage for your objects is located and the file name. (The default location from the Apple template is provided by the applicationDocumentsDirectory method inside the app delegate.)
The usual location for the data store of a non-document-based Core Data application is in ~/Library/Application/Support/com.mydomain.myapp/CocoaAppCD.storedata.
Rename or delete this file (depending on whether its contents are disposable).
Re-launching your application will recreate the file with no data and you can start re-populating it according to your new model.
With production versions of your application, a model change would require a formal lightweight or heavy migration to preserve the user's data.
As a convenience, on startup I print out the location of the database to the console as follows:
// Get / print location of database for use in testing / debugging
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let path = paths[0] + "/LocalStore.sqlite"
print(path.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
Besides being easy to see, I can just select/copy/past this to use in sqliteBrowser.
Choose Finder and go to Library from Go by clicking option button on keyboard. then search on library using your app Bundle Identifier. delete the folder with it. then Re-launching your application will recreate the folder with no data and you can start re-populating it according to your new model.

Problem in working with core data

Am using core data framework in my cocoa application,I have created couple of entities and created reference using NSEntityDescription. When i run the application am getting an error saying that "The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store."
You need to delete the application from your device / simulator, then build and run again.
This will happen each time you change your model, because the old data store will remain in the apps documents folder, while the classes accessing it have been altered.
In a later stage of development, you will propably want to introduce store migration, sou your testers and users won't have to delete their data each time a new version is released. If your model remains static though, you don't need to migrate the data during future updates.
You might want to take a look at the Core Data Migration Programming Guide for further information.
The answer is a bit tricky but this always works for me. This is for a clean installation of a new compatible .sqlite file, not a migration!
launch simulator, delete the app and the data (the popup after you delete the app).
quit simulator
open X-Code, after making any edits to your data model
delete the {*appname*}.sqlite file (or back it up, remove it from project folder, and delete reference)
clean the app (Product > Clean)
Run the app in a simulator (for this tutorial I will assume 4.2)
While the simulator is running, in a Finder window, navigate to:
{*home*} > Library > Application Support > iPhone Simulator > 4.2 > Applications > {*random identifier*} > Documents > {*appname*}.sqlite
Copy this file to another location
Stop running your app in X-Code
Drag and drop the {appname}.sqlite file into the files list in X-Code.
In the dialog that pops up, make sure the copy to folder checkbox, is checked.
Product > Clean
Then run the app in the simulator again
Now you should have a working sqlite file!
Cheers,
Robert
You must delete the persistent store file from either:
~/Library/$AppName
~/Library/Application Support/$AppName
(Depending on your version of Xcode.)

Save Core Data models in Xcode 4

I want to create a new split view-based iOS project from scratch using the template wizard of Xcode 4.0 (build 4A304a). I ticked the "Use Core Data" checkbox. When I try to save the generated test.xcdatamodeld Core Data model, Xcode says The document "test.xcdatamodel" could not be saved.
How can I save the file? I already checked the file system for the proper permissions, but they seem alright.
Aha - I've been suffering from this problem all day and just found the answer. I ran /Applications/Utilities/Console and tried the save again. This error appeared in the console:
AppKit called rmdir("/Users/kris/.TemporaryItems/folders.501/TemporaryItems/
(A Document Being Saved By Xcode)"), it didn't return 0,
and errno was set to 66.
Though I couldn't see anything obviously wrong with this folder (the permissions & ownership looked normal), removing the whole of ~/.TemporaryItems/ allowed me to save again.

Resources