4

我已阅读我的 XCode 数据模型发生任何更改后,我不断收到“保存操作失败”

错误代码:

  This NSPersistentStoreCoordinator has no persistent stores.  It cannot perform a save operation.
 (null)
 (
0   CoreFoundation                      0x36aeb8a7 __exceptionPreprocess + 186
1   libobjc.A.dylib                     0x32f02259 objc_exception_throw + 32
2   CoreData                            0x353a8fe7 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 282
3   CoreData                            0x35411287 -[NSManagedObjectContext save:] + 522
4   myshine                             0x001a1e59 _mh_execute_header + 1293913
5   myshine                             0x0006cacd _mh_execute_header + 27341
6   myshine                             0x000aa829 _mh_execute_header + 280617
7   myshine                             0x000abe07 _mh_execute_header + 286215
8   myshine                             0x0009a12b _mh_execute_header + 213291
9   myshine                             0x00099fb3 _mh_execute_header + 212915
10  myshine                             0x0009ad9b _mh_execute_header + 216475
11  myshine                             0x000978a7 _mh_execute_header + 202919
12  CoreFoundation                      0x36a80533 _signalEventSync + 74
13  CoreFoundation                      0x36a804e1 _cfstream_solo_signalEventSync + 76
14  CoreFoundation                      0x36a80353 _CFStreamSignalEvent + 374
15  CFNetwork                           0x3367b121 _ZN12SocketStream40dispatchSignalFromSocketCallbackUnlockedEP24SocketStreamSignalHolder + 24
16  CFNetwork                           0x33607bb9 _ZN12SocketStream14socketCallbackEP10__CFSocketmPK8__CFDataPKv + 112
17  CFNetwork                           0x33607b39 _ZN12SocketStream22_SocketCallBack_streamEP10__CFSocketmPK8__CFDataPKvPv + 64
18  CoreFoundation                      0x36ac22ef __CFSocketPerformV0 + 638
19  CoreFoundation                      0x36abfad3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 14
20  CoreFoundation                      0x36abf29f __CFRunLoopDoSources0 + 214
21  CoreFoundation                      0x36abe045 __CFRunLoopRun + 652
22  CoreFoundation                      0x36a414a5 CFRunLoopRunSpecific + 300
23  CoreFoundation                      0x36a4136d CFRunLoopRunInMode + 104
24  GraphicsServices                    0x34c08439 GSEventRunModal + 136
25  UIKit                               0x34ceacd5 UIApplicationMain + 1080
26  myshine                             0x00069f0b _mh_execute_header + 16139
27  myshine                             0x000686b0 _mh_execute_header + 9904

)

我的代码:

+ (CoreDataManager *)sharedInstance {
    @synchronized(self) {
        if (instance == nil) {
            instance = [[CoreDataManager alloc] init];
        }
    }
    return instance;
}

-(NSManagedObjectModel *)getmanagedObjectModel:(NSManagedObjectModel *)managedobjectModel
{
    if (managedobjectModel != nil) {
        return managedobjectModel;
    }
   // managedobjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"PushNoticationModel" withExtension:@"momd"];
    managedobjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return managedobjectModel;
}

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator:(NSString*)modelName
{
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }


    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    @"PushNoticationModal.sqlite"
    NSURL *storeUrl = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:modelName]];
    NSError *error = nil;
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:[self getmanagedObjectModel:self.managedObjectModel]];

    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
        NSLog(@"persistentStoreCoordinator Error: %@,%@",error,[error userInfo]);
    }

    return persistentStoreCoordinator;
}

-(NSManagedObjectContext *)managedObjectContext:(NSString*)modelName
{
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator =[self persistentStoreCoordinator:modelName];

    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc]init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }

    return managedObjectContext;
}

-(NSManagedObjectContext *)managedObjectContext:(NSString*)modelName managedObjectContext:(NSManagedObjectContext *)managedContext
{
    if (managedContext != nil) {
        return managedContext;
    }

    NSPersistentStoreCoordinator *coordinator =[self persistentStoreCoordinator:modelName];

    if (coordinator != nil) {
        managedContext = [[NSManagedObjectContext alloc]init];
        [managedContext setPersistentStoreCoordinator:coordinator];
    }

    return managedContext;
}

我用过

-(NSManagedObjectContext *)getManagedObjectContext{


 return  [[CoreDataManager sharedInstance] managedObjectContext:kSqlname managedObjectContext:[CoreDataManager sharedInstance].managedObjectContext];

}

如果我每次都需要修改kSqlname,当我的代码数据添加新字段时?例如,如果修改 sqlname:

NSURL *storeUrl = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:modelName]]; 

如果我需要重命名模型名,例如:version1 modelName=version1.sqlite 当我添加新字段 modelName=version2.sqlite

编辑:我认为不是在不同的线程,因为我测试了很多次没有给我错误,只有其他用户更新版本可能会给出错误

-(void)refreshData{

     NSLog(@"ChatHistoryViewController2333");


        isRefresh=NO;
        AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];



        dispatch_queue_t downloadQueue = dispatch_queue_create("refresh history", NULL);
        dispatch_async(downloadQueue, ^{

            NSManagedObjectContext *managedObjectContext =[self getManagedObjectContext];
            readArray=[[CoreDataManager sharedInstance] readEvent:@"ChatHistoryEntity" SortDescriptor:@"when" managedObjectContext:managedObjectContext];

            __block NSMutableArray *chatArr=[[NSMutableArray alloc]init];

            if(readArray.count>0){
                for(int i=0;i<readArray.count;i++){

    //                ChatHistoryEntity *chatHistoryEntity=[readArray objectAtIndex:(readArray.count-i-1)];
                    ChatHistoryEntity *chatHistoryEntity=[readArray objectAtIndex:i];


                    People *people=[[People alloc]init];

                    people.lastActivity=chatHistoryEntity.lastChat;
                    people.avatarsmall=chatHistoryEntity.avatarsmall;
                    people.when=chatHistoryEntity.when;
                    people.source=chatHistoryEntity.source;
                    people.idName=chatHistoryEntity.idName;

                    people.foreignId=[NSString stringWithFormat:@"%@",chatHistoryEntity.from];
                    NSManagedObjectContext *managedObjectContext =[self getManagedObjectContext];
                    int count=[[CoreDataManager sharedInstance]Count_ChatEventEntity:chatHistoryEntity.from to:delegate.myAuraId managedObjectContext:managedObjectContext];
                     people.readnum=[NSString stringWithFormat:@"%d",count];
                    NSString *distanceStr;
                    if (people.lastActivity) {
                         distanceStr=[ModelClass CheckIsNull:people.lastActivity];
                    }
                    if (chatHistoryEntity.name) {
                         people.screenName=[ModelClass CheckIsNull:chatHistoryEntity.name];
                    }


    //                NSLog(@"distanceStr:%@",distanceStr);
                    if (distanceStr==nil||[distanceStr isEqualToString:@"(null)"]||
                        people.screenName==nil||[people.screenName isEqualToString:@"(null)"]){

                    }else{

                        NSLog(@"people.foreignId=%@  people.screenName=%@  people.source=%@",chatHistoryEntity.from ,chatHistoryEntity.name ,chatHistoryEntity.source);
                        NSLog(@"people.idName=%@",chatHistoryEntity.idName);


                         [chatArr addObject:people];
                    }


                }
            }



            dispatch_async(dispatch_get_main_queue(), ^{



                    if (chatListArry) {
                        chatListArry=[[NSMutableArray alloc]init];
                    }

                    chatListArry=chatArr;
                   if ([chatListArry count]==0) {
                        self.tableView1.hidden=YES;
                        nodataView.hidden=NO;
                    }else{
                        self.tableView1.hidden=NO;
                        nodataView.hidden=YES;
                       [self.tableView1 reloadData]; 
                    }

                  chatArr=nil;


            });

        });
        dispatch_release(downloadQueue);


}
4

1 回答 1

8

我通过修改sql数据库文件名解决了我的问题:

NSURL *storeUrl = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:modelName]];

如果数据库被修改,modelName应该重命名。例如在版本 1modelName = version1.sqlite中。然后在添加一个新字段后,modelName = version2.sqlite

每次在 Core Data 中添加或删除字段时,重命名 sqlite 数据库。

于 2013-03-19T09:21:50.957 回答