ios - RestKit、NSFetchedResultsController 和删除孤立对象

标签 ios objective-c restkit nsfetchedresultscontroller restkit-0.20

我设置了 RestKit 并使用 API 和核心数据正常工作,使用 NSFetchedResultsController 来显示信息。一切都运行良好,除了在服务器上删除本地对象后将其删除。我尝试按照 RestKit 文档使用 RKObjectManager 删除孤立对象,但它似乎不起作用。这就是我所拥有的,任何见解都会很棒:

对象映射

+ (RKMapping *)locationMapping{
//Create object map
//Same mapping as object mapping, but to NSManagedObjects
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Location" inManagedObjectStore:[RKManagedObjectStore defaultStore]];

//Map the identical json / object properties
[mapping addAttributeMappingsFromArray:@[@"name", @"city", @"zip", @"recipient", @"street", @"state"]];

//Map the non-identical properties (left side = json, right side = NSObject)
[mapping addAttributeMappingsFromDictionary:@{
                                              @"id": @"locationID",
                                              @"user_id":@"userID"
                                              }];

[mapping setIdentificationAttributes:@[@"locationID"]];

[mapping addRelationshipMappingWithSourceKeyPath:@"user" mapping:[self userMapping]];
[mapping addConnectionForRelationship:@"user" connectedBy:@"userID"];

RKObjectManager *rkObjectManager = [RKObjectManager sharedManager];

//Delete any orphaned objects
[rkObjectManager addFetchRequestBlock:^NSFetchRequest *(NSURL *URL) {
    RKPathMatcher *pathMatcher = [RKPathMatcher pathMatcherWithPattern:@"/api/v1/:userID/locations"];
    NSDictionary *argsDict = nil;
    if ([pathMatcher matchesPath:[URL relativePath] tokenizeQueryStrings:NO parsedArguments:&argsDict]) {
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Location"];
        return fetchRequest;
    }
    return nil;
}];


return mapping;
}

注意 - 在运行映射或进行 API 调用时,addFetchRequestBlock 不会执行

拉取数据

+(void)loadUserLocations{
//Don't try to load if there is no logged in user
if(![self getCurrentUser])return;

//Create an index of successful status codes
NSIndexSet *statusCodeSet = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);

//Pull location mapping from Mapping Provider
RKMapping *mapping = [MappingProvider locationMapping];

//Determine how rest kit will deal with the response. Specific to API calls
RKResponseDescriptor *rkResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping
                                                                                          method:RKRequestMethodGET
                                                                                     pathPattern:@"/api/v1/users/:userID/locations"
                                                                                         keyPath:nil
                                                                                     statusCodes:statusCodeSet];

//Create the URL & response
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/users/%@/locations", [Statics baseURL], [self getCurrentUser].userID]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

//Create the operation. Pass through AFHttp (more options) or NSURL
//When the request hits the path pattern (in this case, /locations),
//it will use the mapping to create the appropriate items
RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[rkResponseDescriptor]];


//Set the cache
operation.managedObjectCache = [RKManagedObjectStore defaultStore].managedObjectCache;
operation.managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;

[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {

} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    NSLog(@"Response: %@", operation.HTTPRequestOperation.responseString);
}];

[operation start];
}

设置 NSFetchedResultsController

-(NSFetchedResultsController*)fetchedResultsController{
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest *fetchRequest =   [[RKManagedObjectStore defaultStore].managedObjectModel fetchRequestFromTemplateWithName:@"userLocations" substitutionVariables:@{@"USERID":[User getCurrentUser].userID}];

//Sort the request
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                          initWithKey:@"locationID" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

[fetchRequest setFetchBatchSize:20];

//Create a new controller and set it to the VC
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                    managedObjectContext:self.mainMOC sectionNameKeyPath:nil
                                                                               cacheName:@"Root"];
NSLog(@"%@",fetchRequest);

self.fetchedResultsController.delegate = self;

return self.fetchedResultsController;
}

这可能是缓存问题吗?还是我设置不当?

最佳答案

提取请求 block 中的路径模式 /api/v1/:userID/locations 与您的 GET 请求不匹配。

但是您的主要问题是,要使用获取请求 block ,对象管理器需要运行请求。事实上,您正在显式创建请求和操作并执行。您应该完全创建和配置对象管理器,并使用它来发出请求(您编写的代码也应该更少)。

关于ios - RestKit、NSFetchedResultsController 和删除孤立对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746618/

相关文章:

ios - RESTKit 中的 RKResponseDescriptor 已弃用

ios - (const) 变量的范围未定义为 extern 或 static

ios - UITests 在组中运行时失败但在独立运行时成功

ios - 将字节数组从 Swift 转换为 Objective-C 时应该使用什么数据类型

iphone - 如何获取一个巨大的视频文件的切片数据

ios - 使用restkit为预加载的数据库提供种子

ios - RestKit请求映射-发布对象数组

ios - 从 iOS 上的音乐库中获取所有歌曲

ios - 在图像数组 Swift 中来回滑动

ios - 为什么在要求我的 TableView 滚动到顶部时我会收到 NSRangeException?