0

我有一个包含 2 个实体(没有关系)的数据库(核心数据)......在我的情况下插入和获取效果很好......但删除部分让我很困扰......一个实体中的对象被删除,但其他实体没有。 .

这是我的代码:

    -(void)deleteObject:(NSString *)entityDescription //entityDescription get entity name 
       {
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
                        NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:self.managedObjectContext];
                        [fetchRequest setEntity:entity];
                        NSError *errors;
                        NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&errors];
                        NSManagedObject *managedObject=[finalArray objectAtIndex:currentImageIndex];
                        for (int i=0;i<[items count];i++)
                        {
                            if ([managedObject isEqual:[items objectAtIndex:i]])
                            {
                                 [self.managedObjectContext deleteObject:managedObject];
                            }
                        }

                            NSLog(@"%@ object deleted", entityDescription);

                         NSNotificationCenter *nc1=[NSNotificationCenter defaultCenter];
                        [nc1 addObserver:self selector:@selector(deleteCheck:) name:NSManagedObjectContextObjectsDidChangeNotification object:self.managedObjectContext];
NSError *error;
                if (![self.managedObjectContext save:&error])
                {
                    NSLog(@"error occured during save = %@", error);
                }
                else
                {
                    NSLog(@"deletion was succesful");
                } 

这是我的代码,我遵循相同的方法从其他实体中删除对象......实体描述从另一种方法获取不同的实体名称......它适用于一个实体而不适用于另一个......但我得到了managedObjectContext 删除成功消息(bt 未删除 frm DB).. 我该如何解决这个问题?

4

1 回答 1

0

你可以做几件事来缩小范围:

  NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&errors];
  // Add this to see that you are returning items from your fetch
  NSLog(@"%i objects returned in items array",items.count);
  NSManagedObject *managedObject=[finalArray objectAtIndex:currentImageIndex];
  // Add this to see what your fetch is returning
  NSLog(@"Fetch returned %@", managedObject);
  for (int i=0;i<[items count];i++)
  {
     // Add this to see for yourself if it is equal to managedObject
     NSLog(@"Testing: %@",[items objectAtIndex:i]);
     if ([managedObject isEqual:[items objectAtIndex:i]])
     {
        [self.managedObjectContext deleteObject:managedObject];
        // Move this to here so you know each time an object is deleted
        NSLog(@"%@ object deleted", entityDescription);
     }
   }

我怀疑您想测试对象的属性,而不是对象是否相等。无论您是否删除了任何内容,当循环完成时,您都会报告“对象已删除”。如果您打算测试托管对象的属性,请将您的测试更改为:

If ([managedObject.propertyToTest isEqual:[items objectAtIndex:i]])

或每个项目的属性:

If ([managedObject isEqual:[items objectAtIndex:i].propertyToTest])
于 2012-09-24T11:35:38.143 回答