简体   繁体   English

如何在运行时从NSManagedObjectModel生成Core Data访问器类文件(.m / .h文件)?

[英]How can I generate the Core Data accessor class files (.m/.h files) from an NSManagedObjectModel at runtime?

I have an NSManagedObjectModel that I can generate at runtime but can't use it at runtime because I need the class files for the entities. 我有一个NSManagedObjectModel,可以在运行时生成,但不能在运行时使用它,因为我需要实体的类文件。

How can I generate these classes, and maybe stick them in an NSBundle to load them at runtime? 如何生成这些类,以及如何将它们粘贴到NSBundle中以在运行时加载它们?

Thanks! 谢谢!

The best solution is to add Protocols. 最好的解决方案是添加协议。
You do not need the implementation for the managed object class. 您不需要托管对象类的实现。

@protocol NSManagedObjectProtocol <NSObject>
//Add NSManagedObject methods here. Like:
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context
@end

@protocol Person <NSManagedObjectProtocol>
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSDate *birthDate;
@end

Use the protocol to access your objects. 使用协议访问您的对象。
This code would exist in some kind of manager: 此代码将存在于某种管理器中:

NSManagedObjectContext *context = //Get the context.
NSError *error = nil;
id<Person> p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
[p setName:@"PersonName"];
if ([context save:&error]) {
    //Handle error
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM