我的 iPad 应用程序中的功能需要我偶尔清除整个 coredata 数据库。我这样做如下:
+(BOOL)clearEntireDB
{
// Empty all collections
NSArray* stores = [NSArray arrayWithObjects:@"ServerToken",@"Client",@"User",@"Form",@"Company",@"Contact",@"Response",@"Image",@"Thumbnail",@"SearchIndex",@"Tag",@"Literature", nil];
BOOL rc=YES;
for (int i=0;i<stores.count;i++)
{
if (rc==YES)
{
NSString* storeName = (NSString*)[stores objectAtIndex:i];
rc=[HPSDbUtilities clearStore:storeName];
}
}
if (rc==YES)
{
// Now need to delete all files in the document folder
rc = [HPSFileHelper removeAllDocumentFiles];
}
return rc;
}
+(BOOL)clearStore:(NSString*)storeName
{
BOOL rc=NO;
@try{
NSLog(@"HPSDbUtilities::clearStore %@",storeName);
HPSAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = appDelegate.managedObjectContext;
NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:storeName inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (id record in result)
[context deleteObject:record];
NSError* error;
if ([context save:&error] == YES)
{
NSLog(@"HPSDbUtilities::clearStore SAVED");
}else {
NSLog(@"HPSDbUtilities::clearStore NOT saved");
}
rc=YES;
}@catch (NSException * e) {
NSLog(@"clearStore Exception: %@", e);
rc=NO;
}
return rc;
}
该应用程序有一个辅助线程,它使核心数据数据库与网络保持同步。清除整个数据库时,我停止了这个辅助线程。清除数据库后,我再次启动辅助线程。
在我清除数据库之前,辅助线程中的所有处理都可以正常工作。然后辅助线程保存处理开始失败,并出现以下错误:
Error Domain=NSCocoaErrorDomain Code=134030 "The operation couldn’t be completed. (Cocoa error 134030.)" UserInfo=0x261c10 {NSAffectedStoresErrorKey=(
"<NSSQLCore: 0xfe91310> (URL: file://localhost/var/mobile/Applications/3013185E-8171-4A1F-9E1F-6A02E7664510/Documents/Model.sqlite)"
), NSUnderlyingError=0x261b90 "The operation couldn’t be completed. (Cocoa error 4.)", NSFilePath=/var/mobile/Applications/3013185E-8171-4A1F-9E1F-6A02E7664510/Documents/Model.sqlite}
辅助线程代码分布在多个类中,因此我无法在此处真正展示所有内容,但它很简单,只需创建 MOC、更新记录并保存 MOC。
任何人都可以阐明这个问题吗?