How to edit a NSManagedObjectModel that was loaded from a momd in iOS5

安稳与你 提交于 2019-12-03 20:54:51

I filed a radar on this very issue on Oct 5 and received the following response today:

You can get a mutable copy of the model by calling -mutableCopy on the NSManagedObjectModel instance.

This worked on the iOS 5 simulator, I haven't yet tested on a device. Didn't try that myself because NSManagedObjectModel doesn't conform to NSMutableCopying (according to the documentation), and the header file doesn't mention -(id)mutableCopy.

I had worked around it back in October by creating a fresh NSManagedObjectModel by merging the one from the momd file with an empty NSManagedObjectModel. I suppose the models from momd files now are internally immutable, but the others (from copy or merge) are actually mutable.

It's a bug or an undocumented change. I ran this test code:

  NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TestManageObjectModelEdits" withExtension:@"momd"];
  NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  NSEntityDescription *e=[[NSEntityDescription alloc] init];
  [e setName:@"PEntity"];
  NSArray *a=[mom entities];
  NSArray *b=[a arrayByAddingObject:e];
  [mom setEntities:b];
  NSLog(@"mom = %@",mom);

… under iOS 4.3 and 5.0. It works under 4.3 and throws an error saying it can't modify the model file under 5.0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!