我正在使用 Core Data 将持久存储保存在我的应用程序的文档目录中。当我尝试保存托管上下文更改时,收到 Cocoa 错误 134040。这只发生在 Debug模式下的真实 iPhone 上,而不是模拟器上。知道为什么会发生这种情况吗?
这就是我最初在文档目录中创建数据存储的方式。
NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) objectAtIndex:0];
NSURL *userDataStoreURL = [NSURL fileURLWithPath:[documentDirPath
stringByAppendingPathComponent:@"userdata.coredata"]];
userDataStore= [persistentStoreCoordinator_ addPersistentStoreWithType:NSBinaryStoreType
configuration:@"UserData"
URL:userDataStoreURL
options:nil
error:&error];
NSFileManager *fileManager = [NSFileManager defaultManager];
# The following IF statement never executes, so I know the file is being created.
if(![fileManager fileExistsAtPath:[userDataStoreURL path]]) {
NSLog(@"User data file does not exist: %@", [userDataStoreURL path]);
}
这就是我保存上下文的方式:
[managedObjectContext_ save:&error];
这是我在尝试保存托管对象上下文时遇到的错误:
Error Domain=NSCocoaErrorDomain Code=134040 "The operation couldn’t be completed. (Cocoa error 134040.)" UserInfo=0x607b80 {NSAffectedStoresErrorKey=(
"<NSBinaryObjectStore: 0x23f870>",
(
"<NSBinaryObjectStore: 0x23f870>"
)
), NSUnderlyingException=Save partially failed: Directory does not exist or is not writable /var/mobile/Applications/...[app bundle path]}
更多说明
我实际上有 2 个持久存储。一种是只读数据,在升级之间不会改变,并且驻留在主包中。另一个是用户保存的数据存储,它位于文档文件夹内。两个持久存储都属于同一托管对象上下文,但我使用配置仅将某些实体保存到每个持久存储(即,只读实体进入一个,用户保存的实体进入另一个)。
NSPersistentStore *readonlyStore = [persistentStoreCoordinator_
addPersistentStoreWithType:NSBinaryStoreType
configuration:@"ReadOnlyData"
URL:readonlyStoreURL
options:nil
error:&error];
最佳答案
当您遇到错误时,请查找它。这个位于 CoreDataErrors.h 中(还有 FoundationErrors.h 和其他一些):
NSPersistentStoreIncompleteSaveError = 134040, // one or more of the stores returned an error during save (stores/objects that failed will be in userInfo)
因此,您无法保存,userInfo 会告诉您原因。
确实如此。根据你的问题:
NSUnderlyingException=Save partially failed: Directory does not exist or is not writable /var/mobile/Applications/...[app bundle path]}
您正在尝试保存到您的应用程序包中。那是行不通的;您的应用程序包不可写(当然不在设备上)。
您展示了在文档目录中创建持久存储的过程。据我通过阅读得知,这应该有效。您是否还有其他持久性存储,也许您打算默认其内容/从中迁移?如果是这样,请编辑您的问题以包含该代码。
关于iphone - 核心数据 : NSCocoaErrorDomain=134040 Only Occurs On Real Phone, 不是模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7141333/