0

我有带有 xcdatamodeld 的 ios 应用程序,我想更新一些数据,所以需要一个代码

我有插入代码

NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:txtName.text forKey:@"name"];   [newManagedObject setValue:txtid.text forKey:@"id"];     
// Save the context.
NSError *error = nil;
if (![context save:&error]) {      
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

并删除

NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

但我需要更新数据的代码。

4

2 回答 2

1

您可以使用 NSFetchRequest 简单地选择数据(并且可能对描述符和谓词进行排序)。您将返回一个包含该获取请求结果的数组。这些结果都是您从中选择的实体类型,然后您需要做的就是更新这些子类的属性。一个例子是这样的:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntity:@"Car"];
request.predicate = [NSPredicate predicateWithFormat:@"make == %@", @"Ford"]; // make is an attribute of the Car entity

NSArray *fetchResults = [self.fetchedResultsController.managedObjectContext executeFetchRequest:request error:nil];
Car *car = [fetchResults objectAtIndex:0]; // First result
car.make = @"Chevrolet";

现在,您的 Core Data 后端将自动更新为拥有一个品牌为 Chevrolet 的 Car 对象。

于 2012-06-12T18:17:49.070 回答
0
   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];       
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];     

    request.predicate = [NSPredicate predicateWithFormat:@"id == %@", strId];        
    NSArray *fetchResults = [self.fetchedResultsController.managedObjectContext executeFetchRequest:request error:nil];       

    [fetchResults setValue:txtName.text forKey:@"name"];
    [fetchResults setValue:txtPhone.text forKey:@"phone"];
    [fetchResults setValue:txtEmail.text forKey:@"email"];

    NSError *error = nil;
    if (![context save:&error]) {        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
于 2012-06-12T19:27:20.870 回答