ios – 如何通过CoreData模型创建一个新的实体(表)?

我想在SQLite中创建一个新的实体(表).我的代码如下:
+(BOOL)CreateDataSet:(NSManagedObjectModel *) model  
    attributes:(NSDictionary*)attributes 
    entityName:(NSString*) entityName 
{ 
    NSEntityDescription *entityDef = [[NSEntityDescription alloc] init];

    [entityDef setName:entityName];
    [entityDef setManagedObjectClassName:entityName];
    [model setEntities:[NSArray arrayWithObject:entityDef]];
    NSArray *properties =   [CoreDataHelper CreateAttributes:attributes];
    [entityDef setProperties:properties];

    [entityDef release];

    return TRUE;
}

但它会引发错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException',reason: 'Can't modify an immutable model.'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x01c5abe9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x01daf5c2 objc_exception_throw + 47
    2   CoreData                            0x0152634a -[NSManagedObjectModel(_NSInternalMethods) _throwIfNotEditable] + 106
    3   CoreData                            0x01526904 -[NSManagedObjectModel setEntities:] + 36
....

这似乎表明该模型是只读的.

解决方法

From the documentation:(重点是我的)

Managed object models are editable
until they are used by an object graph
manager (a managed object context or a
persistent store coordinator). This
allows you to create or modify them
dynamically. However,once a model is
being used,it must not be changed.
This is enforced at runtime—when the
object manager first fetches data
using a model,the whole of that model
becomes uneditable. Any attempt to
mutate a model or any of its
sub-objects after that point causes an
exception to be thrown. If you need to modify a model that is in use,create a copy,modify the copy, and then discard the objects with the old model.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...