managedObjectContext问题

时间:2010-05-12 09:38:20

标签: iphone sqlite core-data

我有一个应用程序,它是一个UITabBarController,我已经定义了两个子视图

两个选项卡的Identity Inspector中的Class属性都设置为UINavigationController。

现在,经过非常长时间的试验,我已经成功地完成了我的编码。

- (void)viewDidLoad {
[super viewDidLoad];

myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = appDelegate.managedObjectContext;

{



  NSError *error = nil;
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  [fetchRequest setEntity:[NSEntityDescription entityForName:@"User" inManagedObjectContext:self.managedObjectContext]];
  NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

  NSEntityDescription *entityDesc =
  [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.managedObjectContext];

  // replace the old data with new. this DOESNT WORK
  if (fetchedItems.count > 0)
  {
   Usr *newUsr;
   for (newUsr in fetchedItems)
   {
    if ([newUsr.name isEqualToString:@"Line One"])
    {

     newUsr.uName = @"Line One (new)";

    }
   }
  }

  //add a new default data. THIS ADDS DATA TO MY TABLEVIEW BUT IT DOESNT SAVE THEM TO THE SQLITE
  User *addedDefaultdata = nil;
  addedDefaultdata = [[User alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:self.managedObjectContext];
  addedDefaultdata.name = @"Added new 1";
  [addedDefaultdata release];
 }


NSError *error = nil;
if (![User.managedObjectContext save:&error]) {

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

}

我的appdelegate看起来像这样:

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

 [application setStatusBarStyle:UIStatusBarStyleBlackOpaque];


 [window addSubview:navigationController.view];
 [window makeKeyAndVisible];

}

现在我根本无法找到“用户”!虽然我没有错误或警告!

任何建议都会非常感谢!

谢谢

1 个答案:

答案 0 :(得分:0)

您可能会问如何更新到CoreData?

如果是这样,您需要在save:上使用NSManagedObjectContext方法,如下所示:

NSError *error;
[managedObjectContent save:&error];
if (error) {
    ...
}