【问题标题】:Core Data Objective C update content of EntityCore Data Objective C更新Entity的内容
【发布时间】:2012-05-14 17:00:47
【问题描述】:

我是第一次在这里提问,抱歉,我找不到类似的。 所以,我需要更新实体“城市”属性中的数据 - @“名称”。 例如,在我的核心数据中,我已经有 @"New York"、@"Boston"。 通过解析 XML 我有 NSMutableArray *Cities = (@"New York", @"Boston", @"Los Angeles", @"Washington");

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSString *attributeString = @"name";
    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
//save to the TableView
cell.textLabel.text = [[object valueForKey:attributeString] description];
if ((indexPath.row + 1) == numberOfSectionsInTableView && (self.isParsingDone))
        [self.insertNewObjectToCities:nil];
//When coredata updating - tableView is also updating automatically


//Here is just adding new data, but I do not know how to update
- (void)insertNewObjectToCities_translation:(id)sender
{
     NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
NSString *attributeString = @"name";

if (![[self.parseCities.Cities objectAtIndex:i] isEqualToString:[newManagedObject valueForKey:attributeString]])
{
    [newManagedObject setValue:[self.parseCities.Cities objectAtIndex:i] forKey:attributeString];
    NSLog(@"OBBB %@", [self.parseCities.Cities objectAtIndex:i]);
    NSLog(@"dessss %@", [[newManagedObject valueForKey:attributeString] description]);

    i++;

    if (i==[self.parseCities.Cities count]) 
    {
        i = 0;
        return;
    }
    else 
    {
        NSLog(@"valueForKey %@", [newManagedObject valueForKey:attributeString]);
        [self insertNewObjectToCities_translation:nil];
    }
}
else 
{
    NSLog(@"else");
    return;
}

// Save the context.
NSError *error = nil;
if (![context save:&error]) {
    // Replace this implementation with code to handle the error appropriately.
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

}

【问题讨论】:

    标签: objective-c ios core-data


    【解决方案1】:

    要更新托管对象,首先需要获取它,对获取的NSManagedObject 中的字段进行任何更改,然后保存用于获取对象的上下文。如果你再次调用insertNewObjectForEntityForName,它每次都会插入一个新的托管对象,即使它已经存在于Core Data中。

    每次您需要检查是否需要添加新对象时,获取单个对象非常慢。您可能希望将当前已加载的对象(或其唯一标识字段)缓存到 NSArrayNSSet 中,以便您可以检查其成员资格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 2022-01-27
      • 2017-05-16
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多