2013-03-02 3 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 문자열을 저장하겠습니까? –

+0

JSON 도움말을 저장하는 방법은 무엇입니까? –

+0

아, 핵심 데이터의 기존 객체를 반복하여 RKMappingResult * 결과에 표시되는지 확인해 보겠습니다! 어쩌면 도움이 될 것입니다 –

답변

1

서버에서 새 JSON 응답을 받으면 언제든지 코어 데이터 개체에 새 항목을 추가하여 처리해야합니다.

코어 데이터 객체를 반복하고 JSON에 포함되어 있는지 확인한 다음 (객체에 맞는 방법을 사용하여 확인), 그렇지 않은 경우 삭제하십시오.

JSON에서 일종의 ID를 전달하는 경우 코어 데이터에 개체를 추가하는 것과 동시에 NSArray에 각 ID를 저장할 수 있습니다. 그런 다음 배열의 ID와 일치하지 않는 Core Data 객체에 대한 조건부 검색을 수행하고 삭제합니다.

더 나은 것은 기존/신규 항목이 더 많은지 또는 삭제할 항목이 더 많은지에 따라 다릅니다.

+0

대단히 감사합니다. 죄송합니다. 평가할 수 없으며 부족한 담당자가 있습니다.) –

+0

@Paul 담당자의 도움없이 허용 된 답변을 표시 할 수 있어야합니다. ;) 행운을 빕니다. –

관련 문제