'How can I check what is stored in my Core Data Database?

I am making an app that relies on Core Data. I am able to enter data into a text field and store it.

But I need to know if the data is being stored.

I am trying to make a detailView to my tableView and I am not getting any results. Now I am wondering is that because I am doing something wrong with my code, or is the data nto being stored properly.

How can I see what is stored in the app's CoreData database?



Solution 1:[1]

Here is my solution(works on iOS 9):

I use an automator/bash script that open the database in sqllitebrowser. the script finds the latest installed app in the simulator. Instructions:

  1. Install DB Browser for SQLite (http://sqlitebrowser.org/)
  2. Create new workflow in Apple Automator.
  3. Drag "Run Shell script block" and paste this code:
cd ~/Library/Developer/CoreSimulator/Devices/
cd `ls -t | head -n 1`/data/Containers/Data/Application 
cd `ls -t | head -n 1`/Documents
open -a DB\ Browser\ for\ SQLite ./YOUR_DATABASE_NAME.sqlite

enter image description here

  1. (Optional) Convert this workflow to application, save it and drag it to your dock. To refresh the database just click on the app icon.

Solution 2:[2]

Swift 4, 5

Add this line in AppDelegate >> didFinishLaunchingWithOptions function:

print("Documents Directory: ", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found!")

Your modelName.sqlite file will be there.

You can open it with any SQLite browser tools like http://sqlitebrowser.org/ that is free.

Solution 3:[3]

The other solutions are either old or does not direct you easily or quickly to the SQLite files, so I came up with my own solution using FileManager.SearchPathDirectory.applicationSupportDirectory that gets the exact path where the sqlite file will be.

func whereIsMySQLite() {
    let path = FileManager
        .default
        .urls(for: .applicationSupportDirectory, in: .userDomainMask)
        .last?
        .absoluteString
        .replacingOccurrences(of: "file://", with: "")
        .removingPercentEncoding

    print(path ?? "Not found")
}

whereIsMySQLite() will print the path which you can simply copy-paste on your Mac here:

Finder > Go > Go to folder

Solution 4:[4]

The folder where the db is stored has recently been changed and is not where you'd expect to find it. Here's what I used to solve this: First add this code to your viewDidLoad or applicationDidFinishLaunching:

    #if TARGET_IPHONE_SIMULATOR
    // where are you?
    NSLog(@"Documents Directory: %@", [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
    #endif

Got this from here: where is the documents directory for the ios 8 simulator

This will reveal the actual location of your app in the console during runtime. Then use the SQLiteBrowser to check the contents of your SQLite DB.

Worked like a charm for me ;)

Solution 5:[5]

As Far as macOS Sierra version 10.12.2 and Xcode 8 is concerned

The folder should be here:

/Users/$username$/Library/Developer/CoreSimulator/Devices/$DeviceID$/data/Containers/Data/Application/$ApplicationID$/Library/Application Support/xyz.sqlite

To get the device id - Open terminal and paste:

instruments -s devices

Solution 6:[6]

As said before, you can use the sqllite command line tool.

However, you can also set the debug flag, which will dump out all sql commands as they execute through core data.

Edit the scheme, and add this in the "Arguments Passed on Launch"

-com.apple.CoreData.SQLDebug 1

Solution 7:[7]

In Swift 3, you have the the NSPersistentContainer and you can retrieve the path from there like this:

persistentContainer.persistentStoreCoordinator.persistentStores.first?.url

(Assuming you are only using one persistent store)

Solution 8:[8]

1) Get path of sql database of your simulator.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [paths objectAtIndex:0]);

2) Open Finder. Press Cmd+Shift+G. Paste something, that you got from paragraph 1. Ex:

/Users/USERNAME/Library/Developer/CoreSimulator/Devices/701BAC5F-2A42-49BA-B733-C39D563208D4/data/Containers/Data/Application/DCA9E9C7-5FEF-41EA-9255-6AE9A964053C/Documents

3) Download in AppStore programm like SQLPro.

4) Open file in folder with name "ProjectName.sqlite".

GOOD JOB! You will see something like this: enter image description here

Solution 9:[9]

An easy and convenient way to locate the Core Data database and to view and analyse the content, is by using a tool like Core Data Lab.

More info here: https://betamagic.nl/products/coredatalab.html

Disclaimer: I'm the creator of this tool.

Solution 10:[10]

I found the best way to find and open the .sqlite database is use this script:

lsof -Fn -p $(pgrep YOUR_APP_NAME_HERE) | grep .sqlite$ | head -n1

For whatever reason, the output on my Mac always has an extra n character, so I had to copy and paste it to open command. Feel free to modify the above command if you've figured out the right command.

For the best SQLite browser, I'd recommend TablePlus.

Adopted from: https://lukaszlawicki.pl/how-to-quickly-open-sqlite-database-on-ios-simulator/

Solution 11:[11]

Download the SQLite Browser from here.

Run your app in the Simulator. The app should be copied to a path on your Mac that looks like:

/Users/$your username$/Library/Application Support/iPhone Simulator/$your iphone simulator version$/Applications/

Once you locate your app, you have to dig deeper to find the sqlite db (It's usually under Documents).

Solution 12:[12]

An answer for a noobs as I was, I spent quite a lot of time in figuring it out. Steps I followed are :

  1. Open finder and Press Command(Windows) + Shift + G.
  2. Go to the folder add ~/Library/Developer
  3. Search for the DB name you've created as in my case it was my.db in SQLite.
  4. Download and install DB browser for SQLite.
  5. Click open database.
  6. Now drag and drop the DB file from your finder.

Solution 13:[13]

Since no one has pointed out, how to get the sqlite DB from the physical device.

Here is how to get the application data:

Browse the files created on a device by the iOS application I'm developing, on workstation?

After opening the .xcappdata file (right click > Show Package Content), you will usually find the DB file at the AppData/Library/Application Support folder.

Solution 14:[14]

Surprised no one has mentioned this, but assuming your Core Data store is sqlite, you can do a quick & dirty dump of its contents with no 3rd party tools by doing this in Terminal:

$ sqlite3 <path-to-file.sqlite>

// Dump everything
sqlite> .dump

// Dump just one type
sqlite> .dump ZSOMETYPE

// ^D to exit

Solution 15:[15]

I wasn't able to find it in the iPhone Simulator folder. Then I found out the folder by printing the doc path in log:

NSLog(@"The Path is %@", 
  [[[NSFileManager defaultManager] URLsForDirectory:
     NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

and the path turns out be like this :

// /Users/<username>/Library/Developer/CoreSimulator/Devices/<app specific id>/data/Containers/Data/Application/<id>/Documents/coredata.sqlite

Solution 16:[16]

If you've already access to sqlite, shm and wal files then run the commands in the terminal to merge the WAL file into the sqlite file.

$ sqlite3 persistentStore
sqlite> PRAGMA wal_checkpoint;
Press control + d

After running the above commands you can see the data in your sqlite file.


Utility to copy sqlite files to your desktops (do change the desktop path and give the absolute path, the ~ symbol won't work.

For iOS 10.0+ you can use persistentContainer.persistentStoreCoordinator.persistentStores.first?.url

I have created the Utility function that copies the sqlite file to your desired location (works only for simulator). You can use the utility it like

import CoreData


let appDelegate = UIApplication.shared.delegate as! AppDelegate
UTility.getSqliteTo(destinationPath: "/Users/inderkumarrathore/Desktop", persistentContainer: appDelegate.persistentContainer)

Here is definition of utility method for

/**
 Copies the sqlite, wal and shm file to the destination folder. Don't forget to merge the wal file using the commands printed int the console.
 @param destinationPath Path where sqlite files has to be copied
 @param persistentContainer NSPersistentContainer
*/
public static func getSqliteTo(destinationPath: String, persistentContainer: NSPersistentContainer) {
  let storeUrl = persistentContainer.persistentStoreCoordinator.persistentStores.first?.url
  
  let sqliteFileName = storeUrl!.lastPathComponent
  let walFileName = sqliteFileName + "-wal"
  let shmFileName = sqliteFileName + "-shm"
  //Add all file names in array
  let fileArray = [sqliteFileName, walFileName, shmFileName]
  
  let storeDir = storeUrl!.deletingLastPathComponent()
  
  // Destination dir url, make sure file don't exists in that folder
  let destDir = URL(fileURLWithPath: destinationPath, isDirectory: true)

  do {
    for fileName in fileArray {
      let sourceUrl = storeDir.appendingPathComponent(fileName, isDirectory: false)
      let destUrl = destDir.appendingPathComponent(fileName, isDirectory: false)
      try FileManager.default.copyItem(at: sourceUrl, to: destUrl)
      print("File: \(fileName) copied to path: \(destUrl.path)")
    }
  }
  catch {
    print("\(error)")
  }
  print("\n\n\n ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ NOTE ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\n")
  print("In your terminal run the following commands to merge wal file. Otherwise you may see partial or no data in \(sqliteFileName) file")
  print("\n-------------------------------------------------")
  print("$ cd \(destDir.path)")
  print("$ sqlite3 \(sqliteFileName)")
  print("sqlite> PRAGMA wal_checkpoint;")
  print("-------------------------------------------------\n")
  print("Press control + d")      
}

For

/**
 Copies the sqlite, wal and shm file to the destination folder. Don't forget to merge the wal file using the commands printed int the console.
 @param destinationPath Path where sqlite files has to be copied
 @param persistentContainer NSPersistentContainer
 */
+ (void)copySqliteFileToDestination:(NSString *)destinationPath persistentContainer:(NSPersistentContainer *)persistentContainer {
  NSError *error = nil;
  NSURL *storeUrl = persistentContainer.persistentStoreCoordinator.persistentStores.firstObject.URL;
  NSString * sqliteFileName = [storeUrl lastPathComponent];
  NSString *walFileName = [sqliteFileName stringByAppendingString:@"-wal"];
  NSString *shmFileName = [sqliteFileName stringByAppendingString:@"-shm"];
  //Add all file names in array
  NSArray *fileArray = @[sqliteFileName, walFileName, shmFileName];
  
  // Store Directory
  NSURL *storeDir = storeUrl.URLByDeletingLastPathComponent;

  // Destination dir url, make sure file don't exists in that folder
  NSURL *destDir = [NSURL fileURLWithPath:destinationPath isDirectory:YES];
  
  for (NSString *fileName in fileArray) {
    NSURL *sourceUrl = [storeDir URLByAppendingPathComponent:fileName isDirectory:NO];
    NSURL *destUrl = [destDir URLByAppendingPathComponent:fileName isDirectory:NO];
    [[NSFileManager defaultManager] copyItemAtURL:sourceUrl toURL:destUrl error:&error];
    if (!error) {
      RLog(@"File: %@ copied to path: %@", fileName, [destUrl path]);
    }
  }
  
  
  NSLog(@"\n\n\n ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ NOTE ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~\n");
  NSLog(@"In your terminal run the following commands to merge wal file. Otherwise you may see partial or no data in %@ file", sqliteFileName);
  NSLog(@"\n-------------------------------------------------");
  NSLog(@"$ cd %@", destDir.path);
  NSLog(@"$ sqlite3 %@", sqliteFileName);
  NSLog(@"sqlite> PRAGMA wal_checkpoint;");
  NSLog(@"-------------------------------------------------\n");
  NSLog(@"Press control + d");
}

Solution 17:[17]

Just add in viewDidLoad:

debugPrint(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))

Solution 18:[18]

print("Documents Directory: ", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found!")

Please add this line in applicationDidFinishLaunching of AppDelegate. It will give us the path of Documents. But database of core data is in ./Library/Application Support/ with the name projectname.sqlite.

Solution 19:[19]

Open Mac OS terminal and type the following commands

xcrun simctl get_app_container booted com.ondevtratech.PlannerCoreData


xcrun simctl get_app_container booted <bundle <>identifier> 

To open a DB :

brew install --cask db-browser-for-sqlite

Open << App path: sql lite.app >> <<.sqlite DB path>>

For Example : open -a /Applications/DB\ Browser\ for\ SQLite.app /DTMPlanner.sqlite