1

我拼命尝试正确配置 RestKit 核心数据,但我一定做错了,因为当我加载对象时,它们被正确映射但从未持久化。我最终复制/粘贴了 RKTwitterCoreData 示例中的所有内容并得到了以下代码,但我的数据库中仍然一无所获:

- (void)configureRestKit {
    //[[AFHTTPRequestOperationLogger sharedLogger] setLevel:AFLoggerLevelDebug];
    //[[AFHTTPRequestOperationLogger sharedLogger] startLogging];

    // Initialize RestKit
    NSString *serverUrl = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFServerUrl"];
    RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:serverUrl]];
    objectManager.HTTPClient = [CFHTTPClient sharedClient];

    // Enable Activity Indicator Spinner
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

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

    // Setup our object mappings
    /**
     Mapping by entity. Here we are configuring a mapping by targetting a Core Data entity with a specific
     name. This allows us to map back Twitter user objects directly onto NSManagedObject instances --
     there is no backing model class!
     */
    RKEntityMapping *eventMapping = [RKEntityMapping mappingForEntityForName:@"Event" inManagedObjectStore:managedObjectStore];
    eventMapping.identificationAttributes = @[@"eventId"];
    [eventMapping addAttributeMappingsFromArray:@[@"eventId", @"title", @"startDate", @"endDate", @"city", @"country"]];

    [...]

    // Update date format
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"d/M/yyyy"];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [RKObjectMapping setDefaultDateFormatters:[NSArray arrayWithObject:dateFormatter]];

    // Register our mappings with the provider
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:eventMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"events" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
    [objectManager addResponseDescriptor:responseDescriptor];

    [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[Event class] pathPattern:@"event" method:RKRequestMethodPOST]];
    [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[Event class] pathPattern:@"event/:eventId" method:RKRequestMethodGET]];

    /**
     Complete Core Data stack initialization
     */
    [managedObjectStore createPersistentStoreCoordinator];
    NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Chapter4.sqlite"];
    NSError *error;
    NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:@{NSInferMappingModelAutomaticallyOption : @YES, NSMigratePersistentStoresAutomaticallyOption :@YES} 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];
}
4

2 回答 2

3

如果您仍在寻找答案,我今天在 RestKit 0.22.0 中遇到了同样的问题,并通过手动创建 aNSPersistentStoreCoordinatorRKManagedObjectStore用它而不是NSManagedObjectContext.

试试这个(为清楚起见省略了错误检查):

// Model
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

// Manually create a NSPersistentStoreCoordinator
NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

// Add your persistent store to the coordinator
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Chapter4.sqlite"];
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
[persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                              configuration:nil
                                                        URL:storeUrl
                                                    options:nil
                                                      error:nil];

// Init the RKManagedObjectStore with the coordinator
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithPersistentStoreCoordinator:persistentStoreCoordinator];

// Let it create the NSManagedObjectContexts
[managedObjectStore createManagedObjectContexts];

objectManager.managedObjectStore = managedObjectStore;

然后,假设您在 中工作mainQueueManagedObjectContext,将其保存为:

[objectManager.managedObjectStore.mainQueueManagedObjectContext saveToPersistentStore:nil];
于 2014-02-02T08:28:24.627 回答
1

Since RestKit relies on CoreData, you need to save your ManagedObjectContext in order to persist the data. I'm not sure what version you are on, but I saved the data like this:

[[RKObjectManager sharedManager].objectStore.managedObjectContextForCurrentThread save:nil];

Put it inside objectLoaderDidFinishLoading:(RKObjectLoader*)objectLoader, and your objects should be saved.

于 2013-08-22T16:20:29.240 回答