清除iOS核心数据数据库会阻止后续更新

时间:2012-10-19 12:10:51

标签: objective-c ios core-data nsmanagedobject nsmanagedobjectcontext

我的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;
}

该应用程序有一个辅助线程,它使核心数据db与Web保持同步。清除整个数据库时,我会停止此辅助线程。清除数据库后,我再次启动辅助线程。

在清除数据库之前,辅助线程中的所有处理都能正常工作。然后,辅助线程保存处理开始失败,并显示以下错误:

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。

任何人都可以解释这个问题吗?

0 个答案:

没有答案