【问题标题】:can't add sql file while adding core data to my project将核心数据添加到我的项目时无法添加 sql 文件
【发布时间】:2012-10-25 12:00:16
【问题描述】:

我一直在尝试将 Core Data 添加到我现有的 iOS 项目中。我没有现有的 sql 数据库,但我创建了一个数据模型。我按照以下教程进行操作:http://wiresareobsolete.com/wordpress/2009/12/adding-core-data-existing-iphone-projects/

它会在以下代码中产生错误:

(NSPersistentStoreCoordinator *) persistentStoreCoordinator{
if (persistentStoreCoordinator != nil){
    return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentDirectory]
           stringByAppendingPathComponent: @"MyPOC.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                              initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]){
    NSLog(@"Unresolved error OH NO %@, %@", error, [error userInfo]);
}
return persistentStoreCoordinator;
}

我收到以下错误:

2012-10-25 13:52:29.156 MyPOC[1994:11603] Unresolved error OH NO Error
Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. 
(Cocoa error 512.)" UserInfo=0x8246240 {reason=Failed to create file; code = 2}, 
{reason = "Failed to create file; code = 2";}

我真的不知道它为什么会崩溃以及如何解决它。如果需要更多信息来帮助,请告诉我。

【问题讨论】:

  • 检查此问题的已接受答案:stackoverflow.com/questions/6848394/…
  • 您应该检查storeUrl 的值。错误代码很可能意味着您要在其中创建 SQLite 文件的目录不存在。

标签: ios sqlite core-data


【解决方案1】:

我遵循几乎相同的教程并收到相同的错误消息。不过我发现了问题所在。

在我的情况下,无法创建文件,因为 storeURL 路径不正确并指向不存在的文件夹。

在我的辅助方法 [self applicationDocumentDirectory](您在问题中没有提供)中,我输入了示例代码,就像在教程中一样:

- (NSString *) applicationDocumentsDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
}

产生了 URL file:///Users/xxxxxx/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/A6FDD8DB-475B-4C9B-B995-28CCE068DF82/Library/Documentation/

那里有一个愚蠢的代码完成拼写错误,会生成一个无效的路径。你能看见它吗?

是 NSSearchPathDirectory 输入参数的枚举 NSDocumentationDirectory,应该是 NSDocumentDirectory。

正确的代码和网址是:

- (NSString *) applicationDocumentsDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject;
}

网址:file:///Users/xxxxxx/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/A6FDD8DB-475B-4C9B-B995-28CCE068DF82/文档/

【讨论】:

  • 我发现我的旧代码存储在我的电脑上并查看了它。你完全正确!发现错误的好人!
  • 受苦了!不错的地方。对于那些在 iCloud 上工作的人的眼睛和我一样模糊的人:NSDocumentDirectory(不是 NSDocumentationDirectory)。谢谢。
  • 优秀的捕获。这实际上直到今天仍然在苹果官方的核心数据文档中,并且仍然是一个明目张胆的错误。
【解决方案2】:

结束这个问题。 我开始了一个新的核心数据项目并导入了我的其他代码并且它有效。从来没有让它在其他项目中工作。可能忘记了什么,但没有找到什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    相关资源
    最近更新 更多