更新iphone中xcdatamodel中的数据

时间:2012-06-12 18:02:58

标签: ios xcode xcdatamodel

我有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]];

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

2 个答案:

答案 0 :(得分: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后端将自动更新为具有制造雪佛兰的Car对象。

答案 1 :(得分: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();
    }