无法通过iOS保存Core Data对象

时间:2011-07-03 15:43:12

标签: iphone objective-c ios core-data

到目前为止,我成功地保存了核心数据对象。在这段代码中,我正在搜索一些对象,并希望更新或添加属性到保存的对象。

显然它不会保存更改,任何想法为什么?

NSManagedObjectContext *managedObjectContext = ((VentoAppDelegate*) [[UIApplication sharedApplication] delegate]).managedObjectContext;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:EntityNameString inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];

NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
    NSLog(@"Error - Events=nil - %@", [error localizedDescription]);
}
if ([objects count] > 0) {
    for (NSManagedObject* object in objects)    {
        if (distance <= maxDistance) {
            if (bla-bla-bla) {
                [object setValue:[NSNumber numberWithBool:YES] forKey:@"notification"];
                [self saveContext];
            }
        }
    }
}

谢谢!

1 个答案:

答案 0 :(得分:3)

如果更改托管对象,则仅在内存中进行更改。您需要在更改任何内容后保存托管上下文。添加如下内容:

NSError *error;
   if (![object.managedObjectContext save:&error]) {
   // Update to handle the error appropriately.
   NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
   abort();  // Fail
}