2013-03-02 95 views
1

我正嘗試將本地核心數據數據庫與遠程JSON API同步。我使用RestKit將JSON值映射到本地託管對象。這裏是一段代碼:將JSON對象存儲到核心數據中

- (IBAction)testButtonPressed:(id)sender { 

NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil]; 
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel]; 
NSError *error = nil; 
BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error); 
if (! success) { 
    RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error); 
} 

// - - - - - - - - Change the path ! 
NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"AC.sqlite"]; 
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path 
                   fromSeedDatabaseAtPath:nil 
                     withConfiguration:nil 
                       options:nil 
                        error:&error]; 
if (! persistentStore) { 
    RKLogError(@"Failed adding persistent store at path '%@': %@", path, error); 
} 
[managedObjectStore createManagedObjectContexts]; 

// - - - - - - - - Here we change keys and values 
RKEntityMapping *placeMapping = [RKEntityMapping mappingForEntityForName:@"Place" 
                inManagedObjectStore:managedObjectStore]; 
[placeMapping addAttributeMappingsFromDictionary:@{ 
    @"place_id": @"place_id", 
    @"place_title": @"place_title", 
    @"site": @"site", 
    @"address": @"address", 
    @"phone": @"phone", 
    @"urating": @"urating", 
    @"worktime": @"worktime", 
    @"lat": @"lat", 
    @"lng": @"lng", 
    @"about": @"about", 
    @"discount": @"discount", 
    @"subcategory_title": @"subcategory_title", 
    @"subcategory_id": @"subcategory_id", 
    @"category_title": @"category_title", 
    @"image_url": @"image_url"}]; 


//RKEntityMapping *articleMapping = [RKEntityMapping mappingForEntityForName:@"Article" inManagedObjectStore:managedObjectStore]; 
//[articleMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]]; 
//[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"categories" toKeyPath:@"categories" withMapping:categoryMapping]]; 


NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx 
// here we need to change too 
RKResponseDescriptor *responseDescriptor = 
    [RKResponseDescriptor responseDescriptorWithMapping:placeMapping 
              pathPattern:nil // @"/articles/:articleID" 
               keyPath:@"data.place_list" 
              statusCodes:statusCodes]; 

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://allocentral.api.v1.ladybirdapps.com/place/?access_token=19f2a8d8f31d0649ea19d478e96f9f89b&category_id=1&limit=10"]]; 

RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request 
                        responseDescriptors:@[responseDescriptor]]; 

operation.managedObjectContext = managedObjectStore.mainQueueManagedObjectContext; 
operation.managedObjectCache = managedObjectStore.managedObjectCache; 

[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) { 
    NSLog(@" successfull mapping "); 
    [self refreshContent]; 

} failure:^(RKObjectRequestOperation *operation, NSError *error) { 
    NSLog(@"Failed with error: %@", [error localizedDescription]); 
}]; 

NSOperationQueue *operationQueue = [NSOperationQueue new]; 
[operationQueue addOperation:operation]; 
} 

- (void) refreshContent { 
// perform fetch 
NSError *error = nil; 
if (![self.fetchedResultsController performFetch:&error]) { 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 
// reload data 
[self.tableView reloadData]; 
} 

它完美的作品,並得到核心數據中的所有對象,並將它們存儲,但如果某些對象是在服務器上刪除,他們不是在JSON響應,他們留在detebase。我如何使restkit清除不在響應中的對象? thx

+0

也許存儲JSON字符串? – 2013-03-02 19:15:18

+0

如何存儲JSON幫助? – 2013-03-02 19:23:59

+0

哦,我會嘗試迭代核心數據中的現有對象,看看它們是否出現在RKMappingResult *結果中!也許這會幫助 – 2013-03-02 19:26:51

回答

1

無論何時,當您從服務器收到新的JSON響應時,都應該照常處理它,並將新條目添加到Core Data對象中。

然後遍歷Core Data對象,並檢查它們是否包含在JSON中(使用任何適合您的對象的方法),如果沒有,請刪除它們。

或者,如果您使用JSON傳遞某種ID,則可以在將對象添加到Core Data的同時將每個ID存儲在NSArray中。然後對與數組中的ID不匹配的任何Core Data對象執行謂詞搜索,並刪除它們。

哪個更好取決於你是否有更多的新/現有物品或更多的待刪除物品。

+0

非常感謝你,我會去嘗試一下。抱歉,我不能評分,我沒有足夠的代表) – 2013-03-06 07:08:34

+0

@保羅你應該能夠將答案標記爲接受,無論你的代表 - 當然,這是有幫助的。 ;) 祝你好運。 – 2013-03-07 00:27:11