我有一个带有2个实体的数据库(coredata)(没有关系)...在我的情况下插入和取出效果很好..但删除部分让我很烦恼..一个实体中的对象被删除了但是其他的是nt ..
这是我的代码:
-(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");
}
这个我的代码我遵循相同的方法从其他实体中删除对象... entitydescription从另一个方法获取不同的实体名称... Itz适用于一个实体而不是另一个...但我和# 39; m得到managedObjectContext删除成功消息(bt未删除frm DB)..我该如何解决这个问题?
答案 0 :(得分: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])