我有一个设备实体,其中有数据样本
data: {
company = ddd;
name = jje;
version = dd;
})
我想更新公司等于ddd的名称。 这是我的代码。请帮忙
-(IBAction)update:(id)sender
{
NSManagedObjectContext *managedObjectContext = [appdelegate managedObjectContext];
NSEntityDescription *entityDescriptionDelegate = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:managedObjectContext];
NSFetchRequest *requestData = [[NSFetchRequest alloc] init];
[requestData setReturnsObjectsAsFaults:NO];
[requestData setEntity:entityDescriptionDelegate];
NSError *error;
NSArray *objectsArray = [managedObjectContext executeFetchRequest:requestData error:&error];
for (NSManagedObject *object in objectsArray) {
NSLog(@"%@",object);
NSLog(@"%@",objectsArray);
}
答案 0 :(得分:0)
希望它可以提供帮助。将YOUR_VALUE文本更改为实际值
-(IBAction)update:(id)sender
{
NSManagedObjectContext *managedObjectContext = [appdelegate managedObjectContext];
NSEntityDescription *entityDescriptionDelegate = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:managedObjectContext];
NSFetchRequest *requestData = [[NSFetchRequest alloc] init];
[requestData setReturnsObjectsAsFaults:NO];
[requestData setEntity:entityDescriptionDelegate];
[requestData setPredicate:[NSPredicate predicateWithFormat:@"company == YOUR_VALUE"]];
NSError *error;
NSArray *objectsArray = [managedObjectContext executeFetchRequest:requestData error:&error];
for (Device *object in objectsArray) {
object.name = @"YOUR_VALUE";
object.version = @"YOUR_VALUE";
[managedObjectContext save:&error];
}
}
答案 1 :(得分:0)
只需按照以下方式更改循环
for (Device *object in objectsArray) {
object. company = @"newName";
}
[self.managedObjectContext save:nil];
答案 2 :(得分:0)
-(IBAction)update:(id)sender
{
NSManagedObjectContext *managedObjectContext = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
NSEntityDescription *entityDescriptionDelegate = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:managedObjectContext];
NSFetchRequest *requestData = [[NSFetchRequest alloc] init];
[requestData setReturnsObjectsAsFaults:NO];
[requestData setEntity:entityDescriptionDelegate];
NSError *error;
NSArray *objectsArray = [managedObjectContext executeFetchRequest:requestData error:&error];
for (NSManagedObject *object in objectsArray) {
[object setValue:@"Updated Name" forKey:@"name"];
[object setValue:@"Updated version" forKey:@"version"];
}
if (![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}