我想使用核心数据来持久化一些实体,比如事件。
因此我使用类DSManagedObject
和Event
该类DSManagedObject
扩展NSManagedObject
并具有所有实体都可以使用的通用方法。类Event
扩展DSManagedObject
。
下面的代码是DSManagedObject.h
and .m
。中的相关代码.m
就是getContext
-method。
@interface DSManagedObject : NSManagedObject
+ (NSManagedObjectContext *)getContext;
- (NSArray*)getEntitiesForName:(NSString*)_entityName context:(NSManagedObjectContext*)_context;
- (Event*)getEntityForName:(NSString*)_entityName forEventId:(NSInteger)_eventId context:(NSManagedObjectContext*)_context;
- (bool)deleteEntityForName:(NSString*)_entityName forEventId:(NSInteger)_eventId context:(NSManagedObjectContext*)_context;
@end
@implementation DSManagedObject
+ (NSManagedObjectContext *)getContext {
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES],
NSInferMappingModelAutomaticallyOption, nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSURL *storeUrl = [NSURL fileURLWithPath:[basePath stringByAppendingFormat:@"DesertStorm.sqlite"]];
NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
NSError *error = nil;
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
NSLog(@"error loading persistent store..");
[[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:nil];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:persistentStoreCoordinator];
return context;
}
现在在Event
我想调用的类中,initWithEntity
但随后[Event managedObjectModel] unrecognized selector sent to instance
发生错误。什么原因 ?:(
@interface Event : DSManagedObject
@property (assign) NSInteger eventId;
@end
@implementation Event
@dynamic eventId;
- (id)init {
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:[DSManagedObject getContext]];
self = [self initWithEntity:entity insertIntoManagedObjectContext:[DSManagedObject getContext]]; // error occurs
self = [super init];
if (self) {
}
return self;
}
...
@end
我是使用核心数据的新手,所以表现出理解;)感谢您的帮助
PS:如果你想知道我为什么要覆盖init
-method...复杂的原因^^