如何检查存储在核心数据数据库中的内容?

时间:2022-05-30 15:57:28

I am making a app that relies on Core Data. I am able to enter data in a textField and submit it.

我正在开发一个依赖核心数据的应用。我可以在textField中输入数据并提交它。

I was wondering how can I check what is stored in the Database in terms of entries?

我想知道如何检查数据库中存储的条目?

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?

我正在尝试为我的tableView创建一个详细视图,但是我没有得到任何结果。我想知道是因为我的代码出了问题,还是因为数据nto被正确存储了?

Cheers Jeff

欢呼声杰夫

14 个解决方案

#1


20  

If you use sqlite as the storage media for Core Data, you can run your app in simulator and try to check the database file which is located in the sandbox's Library folder.

如果您使用sqlite作为核心数据的存储介质,您可以在模拟器中运行您的应用程序,并尝试检查位于沙箱的库文件夹中的数据库文件。

The path shall be something like: ~/Library/Application Support/iPhone Simulator/5.1/Applications/3BF8A4B3-4959-4D8F-AC12-DB8EF4C3B6E1/Library/YourAppName.sqlite

路径应该是这样的:~/Library/Application Support/iPhone Simulator/5.1/Applications/3BF8A4B3-4959-4D8F-AC12-DB8EF4C3B6E1/Library/YourAppName.sqlite

To open the sqlite file, you need a tool. I use a free tool called Liya (http://itunes.apple.com/us/app/liya/id455484422?mt=12).

要打开sqlite文件,需要一个工具。我使用一个名为Liya的免费工具(http://itunes.apple.com/us/app/liya/id455484422?

#2


26  

Here is my solution(works on iOS 9):

这是我的解决方案(适用于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:

我使用自动/bash脚本在sqllitebrowser中打开数据库。脚本在模拟器中找到最新安装的应用程序。产品说明:

  1. Install DB Browser for SQLite (http://sqlitebrowser.org/)
  2. 为SQLite安装DB浏览器(http://sqlitebrowser.org/)
  3. Create new workflow in Apple Automator.
  4. 在Apple Automator中创建新的工作流。
  5. Drag "Run Shell script block" and paste this code:
  6. 拖动“运行Shell脚本块”并粘贴此代码:
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

如何检查存储在核心数据数据库中的内容?

  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.
  2. (可选)将此工作流转换为应用程序,保存并拖到您的dock中。要刷新数据库,只需单击应用程序图标。

#3


9  

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:

存储db的文件夹最近被更改,而不是您希望找到它的地方。下面是我用来解决这个问题的方法:首先将此代码添加到viewDidLoad或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

从这里得到这个:ios 8模拟器的文档目录在哪里

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.

这将在运行时显示应用程序在控制台中的实际位置。然后使用SQLiteBrowser检查SQLite DB的内容。

Worked like a charm for me ;)

对我来说,这是一种魅力;

#4


6  

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

如前所述,您可以使用sqllite命令行工具。

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

但是,您也可以设置debug标志,它将在执行核心数据时转储所有sql命令。

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

编辑方案,并将其添加到“在启动时传递的参数”中

-com.apple.CoreData.SQLDebug 1

-com.apple.CoreData。SQLDebug 1

#5


5  

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

在Swift 3中,有NSPersistentContainer,可以从那里检索路径,如下所示:

persistentContainer.persistentStoreCoordinator.persistentStores.first?.url

(Assuming you are only using one persistent store)

(假设您只使用一个持久存储)

#6


4  

1) Get path of sql database of your simulator.

1)获取您的模拟器sql数据库路径。

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:

2)开放的发现者。按Cmd + Shift + G。粘贴一些你从第1段得到的东西。例:

/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.

3)像SQLPro一样在AppStore程序中下载。

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

4)在名为“ProjectName.sqlite”的文件夹中打开文件。

GOOD JOB! You will see something like this: 如何检查存储在核心数据数据库中的内容?

好工作!你会看到这样的东西:

#7


4  

Swift 4

斯威夫特4

Add this line in AppDelegate >> didFinishLaunchingWithOptions function:

在AppDelegate >> didFinishLaunchingWithOptions函数中添加这一行:

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

Your modelName.sqlite file will be there.

你的modelName。sqlite文件会在那里。

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

您可以使用任何免费的SQLite浏览器工具(如http://sqlitebrowser.org/)打开它。

#8


3  

Download the SQLite Browser from here.

从这里下载SQLite浏览器。

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

在模拟器中运行你的应用程序。应用程序应该被复制到你的Mac上的路径,如下所示:

/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).

一旦你找到了你的应用,你必须深入挖掘去找到sqlite db(它通常在文档下面)。

#9


2  

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

至于macOS Sierra版本10.12.2和XCode 8

The folder should be here:

文件夹应该在这里:

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

/用户/用户名/图书馆/开发/美元CoreSimulator /设备/的DeviceID美元/数据/集装箱/数据/应用程序/ ApplicationID /图书馆/应用支持美元/ xyz.sqlite

#10


1  

Sorry for the late answer

很抱歉这么晚才给你答复

i wasnt able to find it in the iphone simulator folder. Then i found out the folder by printing the doc path in log .

我在iphone模拟器文件夹里找不到它。然后我通过在日志中打印doc路径找到了这个文件夹。

Code:

代码:

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

NSLog(@“路径是%@”,[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask [lastObject]);

and the path turns out be like this :

路径是这样的:

///Users//Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Documents/coredata.sqlite

/ / /用户/ /图书馆/开发/ CoreSimulator /设备/ /数据/集装箱/数据/应用程序/文档/ coredata.sqlite

#11


1  

An answer for a noobs as I was, I spent 4 months in figuring it out. Steps I followed are :

我花了4个月的时间才弄明白这个问题。我所遵循的步骤如下:

  1. Open finder and Press Command(Windows) + Shift + G.
  2. 打开查找程序并按下命令(Windows) + Shift + G。
  3. Go to the folder add ~/Library/Developer
  4. 进入添加~/Library/Developer文件夹
  5. Search for the DB name you've created as in my case it was my.db in SQLite.
  6. 搜索您创建的DB名称,在我的例子中是我的。在SQLite数据库。
  7. Download and install DB browser for SQLite.
  8. 下载并安装SQLite的DB浏览器。
  9. Click open database.
  10. 点击打开数据库。
  11. Now drag and drop the DB file from your finder.
  12. 现在从查找程序中拖放DB文件。

#12


0  

You may consider print for some quick debugging. (An advantage would be that you can do some simple debugging without leaving XCode.)

您可以考虑使用print进行一些快速调试。(一个优点是您可以在不留下XCode的情况下进行一些简单的调试。)

For example, for an Entity "Animals" with an Attribute "AnimalName", try this -

例如,对于属性为“AnimalName”的实体“Animals”,请尝试以下方法

var animals: [NSManagedObject]!
for var i = 0 ; i < animals.count ; i++ {
    print(animals[i].valueForKey("AnimalName") as! String)
}

#13


0  

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.

如果您已经访问了sqlite、shm和wal文件,那么可以在终端中运行这些命令来将wal文件合并到sqlite文件中。

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

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

运行以上命令后,您可以在sqlite文件中看到数据。


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

对于iOS 10.0+,您可以使用persistentContainer.persistentStoreCoordinator.persistentStores.first

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

我已经创建了实用功能,可以将sqlite文件复制到您想要的位置(仅适用于模拟器)。你可以使用它喜欢的效用

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

这是swift实用方法的定义

/**
 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

为objective - c

/**
 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");
}

#14


0  

Just add in viewDidLoad:

只是加入viewDidLoad:

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

#1


20  

If you use sqlite as the storage media for Core Data, you can run your app in simulator and try to check the database file which is located in the sandbox's Library folder.

如果您使用sqlite作为核心数据的存储介质,您可以在模拟器中运行您的应用程序,并尝试检查位于沙箱的库文件夹中的数据库文件。

The path shall be something like: ~/Library/Application Support/iPhone Simulator/5.1/Applications/3BF8A4B3-4959-4D8F-AC12-DB8EF4C3B6E1/Library/YourAppName.sqlite

路径应该是这样的:~/Library/Application Support/iPhone Simulator/5.1/Applications/3BF8A4B3-4959-4D8F-AC12-DB8EF4C3B6E1/Library/YourAppName.sqlite

To open the sqlite file, you need a tool. I use a free tool called Liya (http://itunes.apple.com/us/app/liya/id455484422?mt=12).

要打开sqlite文件,需要一个工具。我使用一个名为Liya的免费工具(http://itunes.apple.com/us/app/liya/id455484422?

#2


26  

Here is my solution(works on iOS 9):

这是我的解决方案(适用于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:

我使用自动/bash脚本在sqllitebrowser中打开数据库。脚本在模拟器中找到最新安装的应用程序。产品说明:

  1. Install DB Browser for SQLite (http://sqlitebrowser.org/)
  2. 为SQLite安装DB浏览器(http://sqlitebrowser.org/)
  3. Create new workflow in Apple Automator.
  4. 在Apple Automator中创建新的工作流。
  5. Drag "Run Shell script block" and paste this code:
  6. 拖动“运行Shell脚本块”并粘贴此代码:
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

如何检查存储在核心数据数据库中的内容?

  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.
  2. (可选)将此工作流转换为应用程序,保存并拖到您的dock中。要刷新数据库,只需单击应用程序图标。

#3


9  

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:

存储db的文件夹最近被更改,而不是您希望找到它的地方。下面是我用来解决这个问题的方法:首先将此代码添加到viewDidLoad或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

从这里得到这个:ios 8模拟器的文档目录在哪里

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.

这将在运行时显示应用程序在控制台中的实际位置。然后使用SQLiteBrowser检查SQLite DB的内容。

Worked like a charm for me ;)

对我来说,这是一种魅力;

#4


6  

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

如前所述,您可以使用sqllite命令行工具。

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

但是,您也可以设置debug标志,它将在执行核心数据时转储所有sql命令。

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

编辑方案,并将其添加到“在启动时传递的参数”中

-com.apple.CoreData.SQLDebug 1

-com.apple.CoreData。SQLDebug 1

#5


5  

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

在Swift 3中,有NSPersistentContainer,可以从那里检索路径,如下所示:

persistentContainer.persistentStoreCoordinator.persistentStores.first?.url

(Assuming you are only using one persistent store)

(假设您只使用一个持久存储)

#6


4  

1) Get path of sql database of your simulator.

1)获取您的模拟器sql数据库路径。

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:

2)开放的发现者。按Cmd + Shift + G。粘贴一些你从第1段得到的东西。例:

/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.

3)像SQLPro一样在AppStore程序中下载。

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

4)在名为“ProjectName.sqlite”的文件夹中打开文件。

GOOD JOB! You will see something like this: 如何检查存储在核心数据数据库中的内容?

好工作!你会看到这样的东西:

#7


4  

Swift 4

斯威夫特4

Add this line in AppDelegate >> didFinishLaunchingWithOptions function:

在AppDelegate >> didFinishLaunchingWithOptions函数中添加这一行:

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

Your modelName.sqlite file will be there.

你的modelName。sqlite文件会在那里。

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

您可以使用任何免费的SQLite浏览器工具(如http://sqlitebrowser.org/)打开它。

#8


3  

Download the SQLite Browser from here.

从这里下载SQLite浏览器。

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

在模拟器中运行你的应用程序。应用程序应该被复制到你的Mac上的路径,如下所示:

/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).

一旦你找到了你的应用,你必须深入挖掘去找到sqlite db(它通常在文档下面)。

#9


2  

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

至于macOS Sierra版本10.12.2和XCode 8

The folder should be here:

文件夹应该在这里:

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

/用户/用户名/图书馆/开发/美元CoreSimulator /设备/的DeviceID美元/数据/集装箱/数据/应用程序/ ApplicationID /图书馆/应用支持美元/ xyz.sqlite

#10


1  

Sorry for the late answer

很抱歉这么晚才给你答复

i wasnt able to find it in the iphone simulator folder. Then i found out the folder by printing the doc path in log .

我在iphone模拟器文件夹里找不到它。然后我通过在日志中打印doc路径找到了这个文件夹。

Code:

代码:

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

NSLog(@“路径是%@”,[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask [lastObject]);

and the path turns out be like this :

路径是这样的:

///Users//Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Documents/coredata.sqlite

/ / /用户/ /图书馆/开发/ CoreSimulator /设备/ /数据/集装箱/数据/应用程序/文档/ coredata.sqlite

#11


1  

An answer for a noobs as I was, I spent 4 months in figuring it out. Steps I followed are :

我花了4个月的时间才弄明白这个问题。我所遵循的步骤如下:

  1. Open finder and Press Command(Windows) + Shift + G.
  2. 打开查找程序并按下命令(Windows) + Shift + G。
  3. Go to the folder add ~/Library/Developer
  4. 进入添加~/Library/Developer文件夹
  5. Search for the DB name you've created as in my case it was my.db in SQLite.
  6. 搜索您创建的DB名称,在我的例子中是我的。在SQLite数据库。
  7. Download and install DB browser for SQLite.
  8. 下载并安装SQLite的DB浏览器。
  9. Click open database.
  10. 点击打开数据库。
  11. Now drag and drop the DB file from your finder.
  12. 现在从查找程序中拖放DB文件。

#12


0  

You may consider print for some quick debugging. (An advantage would be that you can do some simple debugging without leaving XCode.)

您可以考虑使用print进行一些快速调试。(一个优点是您可以在不留下XCode的情况下进行一些简单的调试。)

For example, for an Entity "Animals" with an Attribute "AnimalName", try this -

例如,对于属性为“AnimalName”的实体“Animals”,请尝试以下方法

var animals: [NSManagedObject]!
for var i = 0 ; i < animals.count ; i++ {
    print(animals[i].valueForKey("AnimalName") as! String)
}

#13


0  

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.

如果您已经访问了sqlite、shm和wal文件,那么可以在终端中运行这些命令来将wal文件合并到sqlite文件中。

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

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

运行以上命令后,您可以在sqlite文件中看到数据。


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

对于iOS 10.0+,您可以使用persistentContainer.persistentStoreCoordinator.persistentStores.first

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

我已经创建了实用功能,可以将sqlite文件复制到您想要的位置(仅适用于模拟器)。你可以使用它喜欢的效用

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

这是swift实用方法的定义

/**
 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

为objective - c

/**
 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");
}

#14


0  

Just add in viewDidLoad:

只是加入viewDidLoad:

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