【问题标题】:Why Isn't Core Data Fetching My Data?为什么 Core Data 不获取我的数据?
【发布时间】:2011-03-29 02:22:22
【问题描述】:

我的实体属性数据在重新启动时未获取或在退出前未保存(可能是任何一种情况)。最重要的是,重新启动时数据未显示在表中。我想我可能需要整合我的核心数据方法或将它们移动到应用程序委托文件中。

我认为我的核心数据代码都搞砸了,谁能帮忙修复它? 如果您需要从 appdelegate.m 等中查看任何其他代码,请告诉我。 这是我的视图控制器的代码:

#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#import "Routine.h"
#import "CurlAppDelegate.h"

@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize managedObjectContext;

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (NSManagedObjectContext *) managedObjectContext {

    if (managedObjectContext != nil) {
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    NSManagedObject *newRoutineEntry;

    newRoutineEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];


    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }

    [eventsArray insertObject:routine atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:context];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

-(void)toggleEdit
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex])
    {
        NSString *entered = [(AlertPrompt *)alertView enteredText];
        if(eventsArray && entered)
        {
            [eventsArray addObject:entered];
            [tableView reloadData];
        }
    }
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellEditingStyleDelete reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row];

    return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }
 }
@end

这是数据模型:

编辑:

添加了 PersisentStoreCoordinater 方法(来自 App Delegate):

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Curl.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

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

    return __persistentStoreCoordinator;
}

【问题讨论】:

  • 能否请您附上您的persistentStoreCoordinator 方法?您的代码中似乎缺少它。另外,您是否故意使用两个不同的托管对象上下文?一个在您的视图控制器中,一个在您的委托中。
  • 我使用从 AppDelegate.m 获得的 persistentStoreCoordinator 方法更新了原始问题。关于两个不同的托管对象,我想我搞砸了,我应该只在应用程序委托中有一个吗?
  • 我真的不认为需要有多个这样的声明。只需通过您的应用程序委托引用这些方法。您还必须在视图控制器中复制 persistantStoreCoordinator 方法,否则 NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 会抛出错误。
  • 好的,所以将我上面发布的persistantStoreCoordinator 方法添加到我的viewController 中?关于托管对象上下文,我认为您的意思是我在addEvent 和viewDidLoad 方法中复制了它?不是应用委托与 viewController?

标签: iphone objective-c core-data


【解决方案1】:

这里有几个技巧可以解决这个问题:

  1. 在您的 RoutineViewController 中删除对 managedObjectContext 等的所有引用。仅引用 AppDelegate 中的 CoreData 类/属性。
  2. 当您需要引用时(例如在您的 AddEvent 方法中)从您的委托中引用适当的对象(参见下面的代码)
  3. 当这变得更加复杂时,您可能需要一个处理所有 CoreData 对象的 DataManager 类。将其设为 Singleton,您将能够在任何类中引用它。为了获取显示的对象,您可以在此类中创建必要的方法以在 NSMutableArray 中检索这些对象

    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] 委托]; NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];

看看您现在是如何使用来自 AppDelegate 的上下文而不是本地的?这很重要,因为您的应用会在初始化时将您的 xdatamodel 从您的 Bundle 链接到您的 AppDelegate。

如果您担心数据未被保存或覆盖,请查看您的 AppDelegate 的 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator

当您退出并进入应用程序时,设置恰好链接到您存储的数据库。这是加载到 Curl.sqlite 文件中的 AppDelegate 中的代码(已修改):

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
if (__persistentStoreCoordinator != nil)
{
    return __persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Curl.sqlite"];

NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{

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

return __persistentStoreCoordinator;

}

【讨论】:

  • 谢谢@Dominic,我现在要试试这个。另外,我对单元格表有疑问,我认为这可能是相关的。问题在这里:stackoverflow.com/questions/5482782/…
  • 好的,从我的 addEvent 方法中,我是否删除以下所有内容?:CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [curlAppDelegate managedObjectContext]; Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context]; NSManagedObject *newRoutineEntry; newRoutineEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];
  • 不,没关系。您正在引用您的 AppDelegate CoreData 属性。所以你很好。
  • @Dominic,谢谢。我很困惑,你说从我的 viewController 中删除所有对 managedObjectContext 的引用。那么我不会删除它吗?
  • 好吧,您仍然需要访问您的 CoreData 模型...我说删除对您本地“managedObjectContext”的引用。现在,您只需要使用“curlAppDelegate 的 managedObjectContext”——它是一个绑定到您的 CoreData 模型的单一上下文。如果可以的话,你应该只使用一个参考,除非你想管理多个模型......
【解决方案2】:

我的猜测是您正在混淆您的托管对象上下文。插入一个并尝试保存另一个。在您的视图控制器中删除您的核心数据相关方法,然后尝试通过您的应用程序委托方法。然后数据将被正确保存,或者Core Data会抛出错误。确保检查您的 Core Data 代码中的任何设置/保存错误。

【讨论】:

  • 谢谢raidfive,所以你建议我从这个viewController 中删除- (NSManagedObjectContext *) managedObjectContext 方法吗?还有什么我需要做的吗?
  • 是的,然后确保您在访问上下文 [appDelegate managedObjectContext] 时通过您的委托。让我知道这是否有助于解决您的储蓄问题。
  • 好的,我试试。在我的viewDidLoad 和addEvent 方法中,我在这两个方法中都有CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];。我应该删除其中一个,哪个?
  • 是的,这是正确的做法。您的 addEvent 方法虽然在您的视图控制器中使用该方法(不确定这是否重要)。见insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];。 managedObjectContext 引用实际上是在调用我让你删除的 getter 方法。
  • @raidfive,感谢您的回复。不过我还是有点困惑。到目前为止,我删除了- (NSManagedObjectContext *) managedObjectContext 方法。我要从 addEvent 中删除什么?就这个Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext]; CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];?
【解决方案3】:

您是否已将核心数据文件附加到主包中? iPhone 应用中有两种类型的 Bundle。主包和应用程序包。我们有一个类似你的场景。我们将数据库复制到我们的主包中,并将数据库的位置写入我们的代码中。然后它工作正常。你也可以检查这个问题。

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多