我有一个数据库(核心数据),有 2 个实体(没有关系)......插入和获取在我的情况下效果很好。.但是删除部分让我很困扰。.一个实体中的对象被删除,但其他实体中的对象是 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");
}
这是我的代码,我遵循相同的方法从其他实体中删除对象......实体描述从另一个方法获取不同的实体名称...Itz 对一个实体运行良好,对另一个实体则不然......但是我收到托管对象上下文删除成功消息(bt 未删除 frm DB)。我该如何解决这个问题?
你可以做一些事情来缩小范围:
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])