[英]How can I generate the Core Data accessor class files (.m/.h files) from an NSManagedObjectModel at runtime?
我有一個NSManagedObjectModel,可以在運行時生成,但不能在運行時使用它,因為我需要實體的類文件。
如何生成這些類,以及如何將它們粘貼到NSBundle中以在運行時加載它們?
謝謝!
最好的解決方案是添加協議。
您不需要托管對象類的實現。
@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
使用協議訪問您的對象。
此代碼將存在於某種管理器中:
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.