iphone - 为什么我无法使用此代码从委托(delegate)获取上下文?

标签 iphone objective-c nsmanagedobject nsmanagedobjectcontext

我从以下代码中得到了一个令人烦恼的模糊错误:

GFree2AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
context = [delegate managedObjectContext];

context定义为NSManagedObjectContext在 .h 文件中和在委托(delegate)中是相同的。似乎包含了所有正确的文件(.m 文件中的 <CoreData/CoreData.h> 除外 - 但无论是否包含,程序都会引发相同的问题。它包含在头文件中。)

包含所有正确的框架和内容 - 当我开始该项目时,我选择了“使用 coredata 来管理数据”或其他任何内容。那么肯定应该没有问题吧?

有更好的方法来完成我想做的事情吗?基本上,我不想继续通过不同的类传递上下文,直到我最终想要使用它(存储数据只是我的应用程序的一小部分)。

在控制台中我得到的错误是:

    2010-08-28 13:09:24.726 GFree2[3912:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
...

    terminate called after throwing an instance of 'NSException'
    Program received signal:  “SIGABRT”.

如果我注释掉该行:context = [delegate managedObjectContext];那么一切似乎都很好。 (目前我还没有实际使用任何 coredata 或任何东西,因此没有更多与之相关的代码。

感谢任何可以提供帮助或对此提供一些见解的人 - 它是如此复杂。

编辑:我的应用程序委托(delegate)文件方法:

#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {

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

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


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel {
  if (managedObjectModel != nil) {
    return managedObjectModel;
  }

  NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"GFree" ofType:@"momd"];
  NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
  managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
  return managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;
  }

  NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"GFree.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;
}

#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
  return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

再次编辑:

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"GFree" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];

是发生错误的行。我不确定这是什么类型的文件,但我确信它显然没有找到它或其他东西......:/有什么想法我应该做什么吗?

@kiamlaluno - 很抱歉回滚您的编辑,不是故意的,只是想看看您更改了什么,并认为这会向我展示......但它显然完全删除了它们。哈哈。

编辑构建结果:

DataModelCompile build/Debug-iphonesimulator/GFree2.app/GFree2.mom GFree2.xcdatamodel
cd "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2"
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/usr/bin/momc -XD_MOMC_TARGET_VERSION=10.6 "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2/GFree2.xcdatamodel" "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2/build/Debug-iphonesimulator/GFree2.app/GFree2.mom"

最佳答案

我认为问题出在您的 GFree2AppDelegate.m 文件中的 persistentStoreCoordinator 方法中。

您能否使用此文件中 managedObjectModelmanagedObjectContextpersistentStoreCoordinator 方法的确切代码更新您的问题?

这些方法是当您选中“使用核心数据进行存储”时由 XCode 生成的。

顺便说一下,您不应该导入 .m 文件。

关于iphone - 为什么我无法使用此代码从委托(delegate)获取上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3590736/

相关文章:

iphone - 如何知道 float 是否有小数

iphone - CoreText 只是一个文本绘制/布局框架吗?

iphone - iOS/核心数据 : How to create a predicate for words that start with a range of characters?

iphone - 如何在url中使用变量

objective-c - UIDocumentInteractionController,没有文件扩展名,只有 UTI

objective-c - 如何在 NSOutlineView 的高亮常规模式下显示显示/隐藏按钮?

iphone - 使用核心数据存储绘制的 map 路径

ios - 将 Web 服务响应数据分配给 NSManagedObject 子类

objective-c - CoreData 是否允许对象图循环? (奇怪的错误)

swift - 创建 NSManagedObject 类的新实例