核心数据给出错误

时间:2012-10-13 02:53:54

标签: ios xcode core-data

我正在使用Core Data并尝试使用简单的数据模型显示数据。该应用程序崩溃并给我这个错误消息

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'+ entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称'Remind''

我不完全确定,但我怎么说它是说它找不到我叫做Remind的实体?但是,我确实有一个名为Remind的实体。

我也放了断点,它就在这里停止:enter image description here

非常感谢任何帮助。完全处于死胡同。

App Delegate .m

中的托管上下文代码

enter image description here

1 个答案:

答案 0 :(得分:1)

这里的问题是您的访问者和您的ivar具有相同的名称。这就是underbar ivar惯例的来源。在这里,您没有使用访问者访问您的属性,您直接使用支持变量,因此它永远不会被初始化。相反,请确保您始终使用访问器方法,并且您不会遇到任何问题。因此,重写违规方法(以及使用managedContextObject属性的任何其他方法,如下所示:

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated]; // it's good practice to call the super methods, even if you're fairly certain they do nothing

  // Get a reference to the managed object context *through* the accessor
  NSManagedObjectContext* context = [self managedObjectContext];

  // From now on, we only use this reference in this method
  NSFetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription* entity = [NSEntityDescription entityForName:@"Remind" inManagedObjectContext:context]; // <- use the local reference we got through the accessor
  [request setEntity:entity];
  NSError* error = nil;
  NSArray* array = [context executeFetchRequest:request error:&error];
  if( !array ) {
    // Do something with the error
    NSLog(@"Error Fetching: %@", error);
  }
  [self setDesitnationsArray:[array mutableCopy]];
  [destinationsTableView reloadData];
}

您可能希望将您的ivars更改为您不想使用的内容,或者您​​很快就会发现自己没有通过访问者,例如_managedObjectContext甚至_privateContext或在你习惯通过访问者访问属性之前,你会发现什么。如果您不喜欢用于访问属性的Objective-C语法,则可以使用点语法,但必须始终记住通过self,例如self.managedObjectContext。我不喜欢这种方法,因为人们忘记了它不是直接属性访问而且它正在使用访问器,因此他们认为可以将点语法交换为直接访问,而不是(就像你的情况一样)。 / p>