具有Core Data和Restkit的多视图控制器

时间:2013-05-22 22:56:59

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

我认为我可能在这里遗漏了一些明显的东西,因为它必须是RestKit的一个非常常见的用例。

我想拥有两个视图控制器,每个控制器只是将NSFetchedResultsController粘贴到UITableView,让我们说第一个显示帖子的时间线,第二个显示特定用户的帖子列表。 我需要为每个视图控制器提供不同的帖子列表,但我无法弄清楚如何使用RestKit获取这些列表。

目前,我在每个视图上使用相同的NSManagedObjectContext,这意味着如果我在视图控制器B中存在但在视图控制器A中没有的帖子,如果我在加载视图控制器B后返回查看控制器A,视图控制器B应该是唯一的帖子现在也显示在视图控制器A中。

我认为我应该做的是为每个视图使用不同的NSManagedObjectContexts,共享一个RKManagedObjectStore,但我无法弄清楚如何让它工作。

这些是我的映射:

RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:managedObjectStore];
[userMapping addAttributeMappingsFromDictionary:@{
    @"avatar_url": @"avatarURL",
    @"id":         @"userID",
    @"first_name": @"firstName",
    @"last_name":  @"lastName",
    @"username":   @"username"
}];
userMapping.identificationAttributes = @[@"userID"];

RKEntityMapping *postMapping = [RKEntityMapping mappingForEntityForName:@"Post" inManagedObjectStore:managedObjectStore];
[postMapping addAttributeMappingsFromDictionary:@{
    @"id":          @"postID",
    @"content_url": @"contentURL",
    @"created_at":  @"createdAt"
}];
postMapping.identificationAttributes = @[@"postID"];
[postMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"creator" toKeyPath:@"creator" withMapping:userMapping]];

[userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"posts" toKeyPath:@"posts" withMapping:postMapping]];

[objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[Post class] pathPattern:@"/posts\\.json" method:RKRequestMethodGET]];
[objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[Post class] pathPattern:@"/posts\\.json" method:RKRequestMethodPOST]];

[objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:postMapping
                                                                             pathPattern:@"/posts.json"
                                                                                 keyPath:nil
                                                                             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

[objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:userMapping
                                                                             pathPattern:@"/_/:username.json"
                                                                                 keyPath:nil
                                                                             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

These are my Core Data entities

(StackOverflow不允许我发布图片......)

在我的视图控制器中,这是我的fetchedResultsController getter

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

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:NO];
    NSArray *sortDescriptors = @[sortDescriptor];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _fetchedResultsController;
}

这是我从时间线视图控制器

发出请求的方式
[[RKObjectManager sharedManager] getObjectsAtPath:@"/posts.json" parameters:nil success:success failure:failure];
// The success and failure blocks don't do all that much, so I've just left them out.

这是我对用户视图控制器的请求

NSString *path = [NSString stringWithFormat:@"/_/%@.json", self.user.username];
[[RKObjectManager sharedManager] getObjectsAtPath:path parameters:nil success:success failure:failure];

2 个答案:

答案 0 :(得分:1)

首先,不要使用/启动路径模式。您在请求中的路径开头也不需要它。

对于实际问题,当您定义NSFetchedResultsController时,还需要为NSPredicate定义fetchRequest。此谓词将允许FRC仅过滤视图控制器实际感兴趣的信息(即使您的数据模型实际上包含的数据多于此数据)。谓词将基于控制器传递的某些值,它应显示...的详细信息。

检查谓词文档here

答案 1 :(得分:0)

@Ross,你做错了的是你没有过滤你的请求,只是得到了所有这些,你必须使用NSPredicate来过滤它。

您需要在视图控制器A和视图控制器B中使用不同的过滤器。

您可以创建类似的内容,例如获取用户的所有帖子:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"creator.username like %@",
       self.user.username];

要获取所有最后的帖子,您甚至不需要谓词,您的sorte描述符必须解决问题。

当您需要向其发送谓词时,这就是您的方法的样子,或者您可以将其直接添加到您已有的方法中。现在这是你的选择。

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

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    [fetchRequest setFetchBatchSize:20];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:NO];
    NSArray *sortDescriptors = @[sortDescriptor];

    [fetchRequest setSortDescriptors:sortDescriptors];

    [fetchRequest setPredicate:predicate];

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _fetchedResultsController;
}

修改 选项 3 - 您可以拥有一个被关注的用户列表,并向用户过滤您的请求,并获取您关注的用户的所有帖子。

您需要首先获得所有被关注的用户,然后您可以使用看起来像这样的子查询来评估您的帖子(我没有测试过,可能出现了问题)

[NSPredicate predicateWithFormat:@"(SUBQUERY(creator, $x, $x.username IN %@).@count > 0)", followedUsernames];

其中followedUsernames是一个包含所有用户名的数组。