我有一个拥有一对多关系的项目。我正在尝试更新Core Data。我有核心数据
添加和更新我使用代码
NSManagedObjectContext *context = [self managedObjectContext];
if (self.contactdb) {
// Update existing device
[self.contactdb setValue:self.name.text forKey:@"name"];
//------------- ???? --------------------
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Name" inManagedObjectContext:context];
[newDevice setValue:self.name.text forKey:@"name"];
for (int i = 0 ; i< appDelegate.TimeOfReceipt.count; i++) {
NSManagedObject *timeinday = [NSEntityDescription insertNewObjectForEntityForName:@"Timeinday" inManagedObjectContext:context];
TimeCell *p1 = [appDelegate.TimeOfReceipt objectAtIndex:i];
[timeinday setValue:p1.dateOfTime forKey:@"timeinday"];
[timeinday setValue:[NSNumber numberWithInt:i] forKey:@"index"];
[timeinday setValue:newDevice forKey:@"name"];
}
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
如何更新Timeinday?
答案 0 :(得分:2)
最好在Xcode中创建托管对象子类,因为它会添加许多适当类型的方法,您可以在与多对多关系集成时使用这些方法。然后,使用这些方法而不是setValue:forKey:
。
在你的情况下,虽然你应该这样做,你的关系是1:to-many,所以你可以设置1端:
[newDevice setValue:timeinday forKey:@"timeinday"];
答案 1 :(得分:1)
NSManagedObjectContext *context = твой контекст;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"name.name like[cd] %@",@"Нужный name у Name"];
NSEntityDescription *ed = [NSEntityDescription entityForName:@"Timeindays" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:ed];
[fetchRequest setPredicate:pred];
fetchRequest.includesPropertyValues = NO;
fetchRequest.includesSubentities = NO;
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"Error requesting items from Core Data: %@", [error localizedDescription]);
}
for (NSManagedObject *managedObject in items) {
[context deleteObject:managedObject];
}
if (![context save:&error]) {
NSLog(@"Error deleting %@ - error:%@", ed, [error localizedDescription]);
}
Илипросто
//Выбери нужный Name, потом:
for (NSManagedObject *managedObject in name.timeinday) {
[context deleteObject:managedObject];
}
if (![context save:&error]) {
NSLog(@"Error deleting %@ - error:%@", ed, [error localizedDescription]);
}