我有一个实际上版本号为2.4的应用程序。从1.0版本开始,我在每个更新中都使用app delegate中的核心数据。所以每次更新我都会在1.0版附带的原始数据库中添加元素。这是添加元素的方式,例如:
//ADD ELEMENT
if (context == nil) { context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; }
Negozi *newElement = [NSEntityDescription insertNewObjectForEntityForName:@"Elements" inManagedObjectContext:context];
newElement.name=@"element name";
newElement.id=@"101";
[context save:nil];
1.0附带的db包括1到100的newElement.id,来自newElement.id 101是在应用程序的一个较新版本中添加的元素。问题来自deletObject。通过这种方式,我可以从我的上下文中删除一个对象:
if (context == nil) { context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; }
NSError *error=nil;
///DELETE Element with id 101
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Elements" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSString *ElementToDelete=[NSString stringWithFormat:@"%@",@"101"];
for (int i=0; i<[fetchedObjects count]; i++) {
if ([[[fetchedObjects objectAtIndex:i] valueForKey:@"id"] isEqualToString:ElementToDelete]) {
[contesto deleteObject:[fetchedObjects objectAtIndex:i]];
}
}
[contesto save:nil];
使用此代码,我可以成功删除id 101中的对象(添加了应用程序更新的对象)。如果我尝试删除id <100的一些元素,我会收到此错误:
CoreData: error: failed to resolve optimistic locking failure: optimistic locking failure with (null)
这是我的托管对象上下文代码:
#pragma mark -
#pragma mark Core Data stack
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel_ != nil) {
return managedObjectModel_;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Elements" withExtension:@"momd"];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Elements.sqlite"];
NSString *storePath = [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"Elements.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Elements" ofType:@"sqlite"];
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:defaultStorePath]];
}
}
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
}
为什么我不能删除最初存储在db?
中的对象答案 0 :(得分:0)
您正在遍历获取结果列表,然后想要修改它(通过删除元素)。这可能会导致您所描述的问题。
相反,清理代码并只获取要删除的元素,而不是所有元素。这消除了循环,也更有效。
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:"Element"];
request.predicate = [NSPredicate predicateWithFormat:@"id = %@", @(101)];
NSArray *result = [context executeFetchRequest:request error:&fetchError];
if (result.count == 1) {
NSManagedObject *element = result.firstObject;
[context deleteObject:element];
[context save:&saveError];
}
else { NSLog(@"Element not found."); }