0
我有一個NSManagedObjectModel,我可以在運行時生成,但不能在運行時使用它,因爲我需要實體的類文件。如何在運行時從NSManagedObjectModel生成核心數據訪問器類文件(.m/.h文件)?
如何生成這些類,並可能將它們粘貼到NSBundle中以在運行時加載它們?
謝謝!
我有一個NSManagedObjectModel,我可以在運行時生成,但不能在運行時使用它,因爲我需要實體的類文件。如何在運行時從NSManagedObjectModel生成核心數據訪問器類文件(.m/.h文件)?
如何生成這些類,並可能將它們粘貼到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
}
想這是有道理的。我的應用程序的其餘部分是使用set____:這樣的選擇器來實現的!謝謝 :) –