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

前端之家收集整理的这篇文章主要介绍了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.

原文链接:https://www.f2er.com/iOS/328029.html

猜你在找的iOS相关文章