如何从RestKit 0.20获取Managed Object上下文

时间:2015-06-09 08:47:43

标签: objective-c core-data restkit-0.20

我正在使用Reskit 0.20,我在appDelegate.m

中创建了这段代码
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self restKitLaunch];
return YES;
}
-(void) restKitLaunch {
// Initialize RestKit
NSURL *baseURL = [NSURL URLWithString:@"http://barcelonaapi.marcpous.com"];
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];

// Initialize managed object model from bundle
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
// Initialize managed object store
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;

// Complete Core Data stack initialization
[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"BusDB.sqlite"];
NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"RKSeedDatabase" ofType:@"sqlite"];
NSError *error;
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];
NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

// Create the managed object contexts
[managedObjectStore createManagedObjectContexts];

// Configure a managed object cache to ensure we do not create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

RKEntityMapping *lineListMapping = [RKEntityMapping mappingForEntityForName:@"Line" inManagedObjectStore:managedObjectStore];
lineListMapping.identificationAttributes = @[ @"line" ];
[lineListMapping addAttributeMappingsFromArray:@[@"line", @"origin", @"destination"]];

RKResponseDescriptor *lineListResponseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:lineListMapping
                                             method:RKRequestMethodGET
                                        pathPattern:@"/bus/lines.json"
                                            keyPath:@"data.tmbs"
                                        statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)
 ];

[objectManager addResponseDescriptor:lineListResponseDescriptor];
}

一切正常,我的sqlite数据库运行良好。问题是我创建了其他实体,我希望以通常的方式使用managedObjectContext添加对象。 如何从此代码创建静态方法以获取托管对象上下文? 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

好的,我发现我可以这样称呼:

NSManagedObjectContext *context = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
当我需要NSManagedObjectContext时,从任何viewController