Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
IOS Coredata唯一约束失败:_Ios_Objective C_Core Data - Fatal编程技术网

IOS Coredata唯一约束失败:

IOS Coredata唯一约束失败:,ios,objective-c,core-data,Ios,Objective C,Core Data,我正试图将数据插入coredata,但我遇到了如下错误: CoreData:错误:(1555)唯一约束失败:ZSIDETABLENAME.Z_PK 情景:- 第一:从appdelegate.m,我正在将数据从我的SQL文件复制到文档目录的SQL文件 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _

我正试图将数据插入coredata,但我遇到了如下错误:

CoreData:错误:(1555)唯一约束失败:ZSIDETABLENAME.Z_PK

情景:-

第一:从appdelegate.m,我正在将数据从我的SQL文件复制到文档目录的SQL文件

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }


   //  Create the coordinator and store

        NSString* from;
        NSString* to;
        NSArray* mainPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [mainPath objectAtIndex:0]; // Get documents folder
        /*VoiceRecords.plist file*/
        from=[[NSBundle mainBundle]pathForResource:@"News" ofType:@"sqlite"];
        to=[documentsDirectory stringByAppendingPathComponent:@"News.sqlite"];
        [[NSFileManager defaultManager]copyItemAtPath:from
                                               toPath:to error:nil];
        from=nil;
        to=nil;

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"News.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}
它工作正常。然后我尝试将用户在coredata中输入的url保存到mainviewcontroller.m中

- (void)feedParserDidFinish:(MWFeedParser *)parser {

        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"IWorld"];
                fetchRequest.predicate = [NSPredicate predicateWithFormat:@"feedurl = %@", self.Feedlink];
        NSManagedObjectContext *context = [self managedObjectContext];

      if ([[context executeFetchRequest:fetchRequest error:NULL] count] == 0) {
                NSError *error = nil;

            NSPredicate *predicate=[NSPredicate predicateWithFormat:@"feedurl contains %@",check];
            [fetchRequest setPredicate:predicate];
              NSMutableArray *checkp = [[context executeFetchRequest:fetchRequest error:&error]mutableCopy];


            if (checkp.count<=0) {
                NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"IWorld" inManagedObjectContext:context];
                [newDevice setValue:self.Name forKey:@"name"];
                [newDevice setValue:self.WebsiteName forKey:@"websitename"];
                [newDevice setValue:self.Feedlink forKey:@"feedurl"];

                                   // Save the object to persistent store
                if (![context save:&error]) {
                    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
                }
                    //Save value in lockbox

                NSArray *keys = [[[newDevice entity] attributesByName] allKeys];
                NSDictionary *dict = [newDevice dictionaryWithValuesForKeys:keys];

            }

        }


     NSFetchRequest *fetchrequestforside=[NSFetchRequest fetchRequestWithEntityName:@"Sidetablename"]; //Sidetablename is entity
    fetchrequestforside.predicate=[NSPredicate predicateWithFormat:@"feedurl = %@", self.Feedlink];
             NSManagedObjectContext *context = [self managedObjectContext];
    if ([[context executeFetchRequest:fetchrequestforside error:NULL] count] == 0) {
                    // Create a new managed object

                    NSError *error = nil;

                    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"feedurl contains %@",check ]; //check is urlstring
                    [fetchrequestforside setPredicate:predicate];
                    NSMutableArray *checkp = [[context executeFetchRequest:fetchrequestforside error:&error]mutableCopy];


                    if (checkp.count<=0) //if coredata will find url then notstore in coredata else stored procedure
          {

                    NSManagedObject *newDevice1 = [NSEntityDescription insertNewObjectForEntityForName:@"Sidetablename" inManagedObjectContext:context];

                    if (self.Name)
                    {
                        [newDevice1 setValue:self.Name forKey:@"name"];


                    }
                    if (self.WebsiteName)
                    {
                        [newDevice1 setValue:self.WebsiteName forKey:@"websitename"];

                    }

                    if (self.Feedlink)
                    {
                        [newDevice1 setValue:self.Feedlink forKey:@"feedurl"];

                    }




                    NSError *error = nil;
                    if (![context save:&error]) {
                            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]); // Getting error here through nslog //CoreData: error: (1555) UNIQUE constraint failed: ZSIDETABLENAME.Z_PK

                        }
-(void)feedparserrdfinish:(MWFeedParser*)解析器{
NSFetchRequest*fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@“IWorld”];
fetchRequest.predicate=[NSPredicate predicateWithFormat:@“feedurl=%@”,self.Feedlink];
NSManagedObjectContext*上下文=[self-managedObjectContext];
if([[context executeFetchRequest:fetchRequest错误:NULL]计数]==0){
n错误*错误=nil;
NSPredicate*谓词=[NSPredicate谓词格式:@“feedurl包含%@”,选中];
[FetchRequestSetPredicate:谓词];
NSMutableArray*checkp=[[context executeFetchRequest:fetchRequest错误:&错误]mutableCopy];

如果(checkp.count您在sidetablename表上遇到主键约束冲突

因此,我相信您的问题在于如何创建和复制种子数据库

不幸的是,你没有提供这些信息。因此,我只能猜测你是如何做到的

我假设您是使用mac应用程序创建数据库的,或者是在iOS模拟器中创建的,然后将sqlite文件从创建位置复制到捆绑资源中

由于自iOS/OSX 7/10.9以来,WAL一直是默认模式,因此我假设您在WAL模式下创建了种子数据库。这意味着您可能丢失了-WAL和-shm文件。如果您指定任何数据属性都应使用外部存储,那么您也会丢失该数据

创建要复制的种子数据库时,还需要复制-shm/wal文件,或者需要在回滚日志模式下创建数据库,该模式将在文件中添加所有数据

您可以在添加持久存储时设置以下选项来实现这一点(如果您已经使用了选项,只需将此选项与其他选项合并即可)

这是在创建要复制到捆绑包中的数据库时添加持久存储的方式。它将确保所有内容都在实际的数据库文件中

现在,在您运行代码创建种子文件后,您应该转到该目录,看看是否还有其他文件。最好的方法是在终端中。转到该目录并执行“ls-lat”,它将列出按时间排序的所有文件

注意事项:根据两个实体的配置,SQLite和Core Data都可以创建与SQLite文件一起使用的额外文件。因此,一般来说,您应该将每个Core Data持久存储视为一个文件包。换句话说,您应该只为Core Data存储创建一个单独的目录。这样,当SQLite或core data决定创建额外的文件,所有内容都限制在单个目录中

当您将文件复制到bundle资源中时,您需要确保复制所有内容,从中创建种子数据库

同样,您应该在部署时将捆绑包中的所有内容复制到设备

但是,不使用文件系统,您应该在<代码> nSistStutsStutoCeCurror < /C> >…/P>上考虑这些方法。

/* Used for save as - performance may vary depending on the type of old and
   new store; the old store is usually removed from the coordinator by the
   migration operation, and therefore is no longer a useful reference after
   invoking this method
*/
- (NSPersistentStore *)migratePersistentStore:(NSPersistentStore *)store
                                        toURL:(NSURL *)URL
                                      options:(nullable NSDictionary *)options
                                     withType:(NSString *)storeType
                                        error:(NSError **)error;

/* copy or overwrite the target persistent store in accordance with the store
   class's requirements.  It is important to pass similar options as
   addPersistentStoreWithType: ... SQLite stores will honor file locks, journal
   files, journaling modes, and other intricacies.  Other stores will default
   to using NSFileManager.
 */
- (BOOL)replacePersistentStoreAtURL:(NSURL *)destinationURL
                 destinationOptions:(nullable NSDictionary *)destinationOptions
         withPersistentStoreFromURL:(NSURL *)sourceURL
                      sourceOptions:(nullable NSDictionary *)sourceOptions
                          storeType:(NSString *)storeType
                              error:(NSError**)error NS_AVAILABLE(10_11, 9_0);


因此,我相信,如果您正确地创建数据库,然后将其完全正确地复制到资源包和应用程序中,那么您的问题就会消失。

我在后台线程上创建/更新coredata实体时遇到了这个错误,在主线程上执行同样的操作解决了这个问题。

根据error消息,您已将属性sidetablename设置为唯一,并且正在尝试保存另一个与属性sidetablename具有相同值的对象。是否已通过调试器查看要保存的对象中的内容以及实际核心数据数据库中的内容?您在尝试自诊断时做了哪些工作问题?这些测试的结果是什么?当在调试器中单步执行时,您看到了什么?您是如何创建要复制的SQLite文件的?@TomHarrington先生,我从文档目录中获取了sql文件,在其中输入了静态数据,然后将其复制到捆绑包中,然后在应用程序第一次启动时,我是copying数据。@JodyHagins是的,先生,我已经用调试器尝试过了。数据没有存储在sqlfile中。因为当调试器运行
if(![context save:&error])时,它会
这种方法我在nslog中遇到错误。但是我可以通过fetch请求获取它。但是当应用程序再次启动时,所有数据都丢失了。这是一种猜测!对的,先生。真的很好,先生。谢谢你,先生。非常感谢。我正在使用CoreData,而创建数据库是ios自己做的事情。我有时会遇到这种错误“CoreData:错误:(1555)唯一约束失败:”。你能帮助我吗,我不明白你是如何解决这个问题的?我正在将sqlite shm和sqlite wam文件从Boundle复制到Documents文件夹,但唯一错误仍然存在。有什么建议吗?我删除了我的应用程序并再次运行该项目,它对我没有任何问题。谢谢
/* Used for save as - performance may vary depending on the type of old and
   new store; the old store is usually removed from the coordinator by the
   migration operation, and therefore is no longer a useful reference after
   invoking this method
*/
- (NSPersistentStore *)migratePersistentStore:(NSPersistentStore *)store
                                        toURL:(NSURL *)URL
                                      options:(nullable NSDictionary *)options
                                     withType:(NSString *)storeType
                                        error:(NSError **)error;

/* copy or overwrite the target persistent store in accordance with the store
   class's requirements.  It is important to pass similar options as
   addPersistentStoreWithType: ... SQLite stores will honor file locks, journal
   files, journaling modes, and other intricacies.  Other stores will default
   to using NSFileManager.
 */
- (BOOL)replacePersistentStoreAtURL:(NSURL *)destinationURL
                 destinationOptions:(nullable NSDictionary *)destinationOptions
         withPersistentStoreFromURL:(NSURL *)sourceURL
                      sourceOptions:(nullable NSDictionary *)sourceOptions
                          storeType:(NSString *)storeType
                              error:(NSError**)error NS_AVAILABLE(10_11, 9_0);