Sqlite文件位置核心数据

时间:2014-06-10 04:45:34

标签: ios objective-c swift sqlite core-data

通常,核心数据应用的sqlite存储文件位于

  

图书馆>应用程序支持> iPhone模拟器> 7.1(或您使用的任何版本)>应用程序>(无论哪个文件夹包含您的应用)>文档

文件夹,但我无法在IOS 8中找到它。我认为他们只会在iPhone模拟器文件夹中添加一个8.0文件夹,但它不在那里。有没有人找到它?

21 个答案:

答案 0 :(得分:123)

我设法找到sqlite文件,现在它在此路径中:

  

Library / Developer / CoreSimulator / Devices /(数字和字母)/ data / Containers / Data / Application /(数字和字母)/ Documents /

(数字和字母)代表一个应用程序/计算机独有的文件夹,但如下所示:779AE2245-F8W2-57A9-8C6D-98643B1CF01A

我可以通过进入appDelegate.m找到它,向下滚动到

- (NSURL *)applicationDocumentsDirectory 

方法和NSLogging返回路径,如下所示:

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory  inDomains:NSUserDomainMask] lastObject]);

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
 }

这将为您提供独特的路径,让您更轻松,因为使用2个未命名的文件夹/字母和数字字符串来定位它是很棘手的。

Swift 4.2:

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
print(paths[0])

答案 1 :(得分:51)

试试这个简单的3步

  1. didFinishLaunchingWithOptions appdelegate.m中复制以下代码,并在NSLog()

    之前添加一个断点
    (BOOL)application:(UIApplication *)application  
    
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",[paths objectAtIndex:0]);
     }
    
  2. 或者在Swift中:

    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    print(paths[0])
    

    enter image description here

    2.Open Finder-> Go - >转到文件夹并粘贴从步骤1复制的路径

    enter image description here

    3。呀!您在目的地。

答案 2 :(得分:45)

没有一个答案提到了实际获取DB文件位置的最简单方法。

它甚至不需要您修改源代码,因为它是XCode中的简单运行时开关。

  1. 选择“运行”按钮旁边的“编辑方案...”。

    edit scheme

  2. 选择Run / Arguments并添加以下两个选项:

    -com.apple.CoreData.SQLDebug 1
    -com.apple.CoreData.Logging.stderr 1
    

    option

  3. 运行该应用,您将在日志中看到:

    logs

答案 3 :(得分:37)

如果您的应用使用核心数据,只需在终端中搜索sqlite文件:

find ~ -name app_db_file_name.sqlite

结果将列出包含您的应用的模拟器文件夹的完整路径。

答案 4 :(得分:20)

我攻击了这个单行(Gist): find ~/Library/Developer/CoreSimulator/Devices/ -name device.plist -exec sh -c "/usr/libexec/PlistBuddy -c \"print UDID\" '{}' | tr '\n' ' '" \; -exec sh -c "/usr/libexec/PlistBuddy -c \"print name\" '{}' | tr '\n' ' '" \; -exec sh -c "/usr/libexec/PlistBuddy -c \"print runtime\" '{}' | sed -n 's/com\.apple\.CoreSimulator.SimRuntime\.\(.*\)/\1/p'" \;

打印:

14F313C8-3813-4E38-903E-2010C136B77B iPad Retina iOS-8-0
1F6B82A2-C467-479A-8CAF-074BE507AC8E iPad Air iOS-8-0
2DA83944-BE5D-4342-B330-08F67A932D8C iPad 2 iOS-7-1
48703432-A5C5-4606-9369-0D21B53EB1E8 iPhone 4s iOS-7-1
4AFB71CC-6752-4F9A-A239-4DC9CA53A8B8 iPhone 5s iOS-8-0
53A65771-DF50-4A5C-A8D2-4D1C3A5D0F60 iPhone 5 iOS-7-1
6B97C174-5914-4E89-8D17-943F0E2703BA iPhone 5 iOS-8-0
6C2DF3E9-FA26-4391-8B66-72E1467D6297 iPad 2 iOS-8-0
7F85E299-A3C2-4704-8B44-2984F6F995F5 iPad Retina iOS-7-1
8B9EDFFD-2240-476B-88AD-06ABE8F9FF51 iPhone 6 Plus iOS-8-0
97691E5D-5C38-4875-8AA7-C2B1E4ABCBB5 Resizable iPhone iOS-8-0
9BBF3408-6CA4-4CE0-BD4E-B02001F1262B iPhone 5s iOS-7-1
C9237847-F0AA-44BC-A74E-C08C2E0F7A6C Resizable iPad iOS-8-0
CC44C1BA-F39C-4410-AE34-4ABBD7806D45 iPad Air iOS-7-1
CDF4D811-5011-4464-8291-5CDA378375EA iPhone 6 iOS-8-0
E77DE00C-E244-4F25-A5E2-E6581614D5A2 iPhone 4s iOS-8-0

<强>更新

当有人指出here时,也可以运行xcrun simctl list devices来获得类似的结果:

== Devices ==
-- iOS 7.0 --
-- iOS 7.1 --
    iPhone 4s (48703432-A5C5-4606-9369-0D21B53EB1E8) (Shutdown)
    iPhone 5 (53A65771-DF50-4A5C-A8D2-4D1C3A5D0F60) (Shutdown)
    iPhone 5s (9BBF3408-6CA4-4CE0-BD4E-B02001F1262B) (Shutdown)
    iPad 2 (2DA83944-BE5D-4342-B330-08F67A932D8C) (Shutdown)
    iPad Retina (7F85E299-A3C2-4704-8B44-2984F6F995F5) (Shutdown)
    iPad Air (CC44C1BA-F39C-4410-AE34-4ABBD7806D45) (Shutdown)
-- iOS 8.1 --
    iPhone 4s (0763EF65-DD0D-4FAD-84C7-2DE63D416526) (Shutdown)
    iPhone 5 (868ED444-8440-4115-AF37-F419CC682D2F) (Shutdown)
    iPhone 5s (E0455E5D-7315-4EC8-B05E-76284728244C) (Shutdown)
    iPhone 6 Plus (72554908-FF99-4B8F-9B87-65255ED08CFC) (Shutdown)
    iPhone 6 (32AA8133-53A4-4BE0-8CE5-0C7A87E81CAF) (Shutdown)
    iPad 2 (4AF84DE8-CBA2-47AE-A92A-0C0CEF9F41F8) (Booted)
    iPad Retina (69238B44-AAFD-4CD5-AAEA-C182D0BC300D) (Shutdown)
    iPad Air (E580AD99-0040-4EC1-B704-0C85567E6747) (Shutdown)
    Resizable iPhone (32E872FC-6513-41AB-A5B9-B23EB7D10DC8) (Shutdown)
    Resizable iPad (99997922-4A9F-4574-9E3E-EF45F893F4A2) (Shutdown)

答案 5 :(得分:17)

如果你正在使用 Swift ,这将返回文档目录的绝对路径:

func applicationDirectoryPath() -> String {
    return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String
}

答案 6 :(得分:13)

我编写了一个bash脚本,用于在模拟器中查找Application文件夹和Application数据文件夹的位置,您可以下载它here。解压缩脚本后,您可以导航到脚本所在的文件夹并使用它。如果您在没有选项的情况下调用它,它将为您提供已安装的iOS模拟器列表。然后,您可以使用这些选项来查找您的程序。写作:

./simulatorAppFolders -s "iPad Air" -i iOS-8-0 -a <MyApp>

将在iPad Air iOS 8模拟器上找到应用程序的应用程序文件夹和主区域文件夹。这是一个例子:

MacBook-Air:_posts user$ ./simulatorAppFolders -s "iPad Air" -i iOS-8-0 -a MyApp
App folder = /Users/james/Library/Developer/CoreSimulator/Devices/6A9DEE93-FAEF-4BF4-9989-BC14CD38AEA0/data/Containers/Bundle/Application/8F64CD7F-A227-43D6-98AC-41D3919827CB
dataFolder = /Users/james/Library/Developer/CoreSimulator/Devices/6A9DEE93-FAEF-4BF4-9989-BC14CD38AEA0/data/Containers/Data/Application/96C40A21-5A5C-4399-839C-B155B8A72932

更新

原始脚本的更新允许您使用-d选项基于设备类型进行搜索。我还编写了另一个脚本,它创建了一系列明智的命名文件夹,以便您可以找到您的应用程序和应用程序文档。 This script将在您的家庭区域中创建一个名为iOS_SIMULATORS的文件夹,您可以从那里轻松导航到您的应用程序。

答案 7 :(得分:6)

我能够使用下一个控制台输出找到simulators文件夹:

NSLog(@"app dir: %@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

在我的情况下是(Xcode 6 beta)

app dir: file:///Users/user/Library/Developer/CoreSimulator/Devices/D00C56D4-DDA3-47B0-9951-27D3B9EC68E8/data/Applications/6ABF3E54-37F5-4AD1-A223-F7467F601FB6/Documents/

答案 8 :(得分:6)

基于Michaels的答案,这是针对Swift 3的

    func applicationDirectoryPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
    }

答案 9 :(得分:5)

适用于Swift 3.0

theme

你可以在Xcode 8.2中获得Coredata的位置

答案 10 :(得分:4)

在Xcode的新更新后,我发现sql文件现在存储在新文件夹 /Library/Application Support 中,这可能是一种独特的情况但是如果你没有在文件夹中找到sql文件在这里搜索:

~/Library/Developer/CoreSimulator/Devices/[@device_id@]/data/Containers/Data/Application/[@application_id@]/Library/Application Support/

将其存储在 Documents 文件夹中:

~/Library/Developer/CoreSimulator/Devices/[@device_id@]/data/Containers/Data/Application/[@application_id@]/Documents/

答案 11 :(得分:4)

对于SWIFT 3:

将此代码复制粘贴到 didFinishLaunchingWithOptions

 print(NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as String)

答案 12 :(得分:3)

对于swift 3

print(NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as String)

答案 13 :(得分:2)

James Snook一样,我创建了自己的脚本,以便更轻松地访问模拟器应用。我觉得除了我之外,很多人来这里都很方便。

与他的脚本不同,我的脚本不是搜索工具,它创建了一个包含所有设备/运行时的完整(和人类可读)文件夹结构,并将软链接添加到其中的应用程序中。

你可以得到它in this Gist

每次在模拟器中安装应用程序时运行它,或者每次因任何原因(它将更新,并在Finder中打开设备文件夹)运行它时运行它。

答案 14 :(得分:1)

如果您尚未指定任何目录,则可以使用以下代码打印默认目录:

打印(NSPersistentContainer.defaultDirectoryURL())

答案 15 :(得分:1)

迅速4.2

我已经为NSPersistentStoreDescription

创建了扩展名
import CoreData

extension NSPersistentStoreDescription {
    func getDatabaseLocation() -> String? {
        return self
            .url?
            .absoluteString
            .replacingOccurrences(of: "file://", with: "") // Remove file suffix
            .replacingOccurrences(of: "%20", with: "\\ ") // Make the spaces to support terminal paste
    }
}

然后我在初始化NSPersistentContainer

时使用它
lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "CoreDataDemo")
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            
            #if DEBUG
            debugPrint(storeDescription.getDatabaseLocation() ?? "No database location")
            #endif
            
            if let error = error as NSError? {
                assertionFailure("Unresolved error \(error), \(error.userInfo)")
            }
        })
        
        return container
    }()

答案 16 :(得分:0)

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

我创建了Utility函数,它将sqlite文件复制到您想要的位置(仅适用于模拟器)。

您可以像

一样使用它
import CoreData


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

如果您已经访问过sqlite,shm和wal文件,则运行终端中的命令将WAL文件合并到sqlite文件中。

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

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

以下是

的效用方法的定义
/**
 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")      
}

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

答案 17 :(得分:0)

Swift 3.x

AppDelegate 文件中找到 didFinishLaunchingWithOptions 功能,然后在此处输入此代码。

let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
print("\(path)")

答案 18 :(得分:0)

Swift 4.x

    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    print(paths[0])

答案 19 :(得分:0)

Swift 4.2

source.pipe(map(x => x * 2), catchError(() => of('ups')))

答案 20 :(得分:-1)

您可以使用以下代码。

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    **print(persistentContainer.persistentStoreDescriptions)**
    return true
}

它将打印核心数据持久存储(即sqlite)的位置