如何在segue中从Core Data获取结果

时间:2013-07-03 04:47:19

标签: ios core-data restkit nsfetchedresultscontroller segue

我有一个使用CoreData和Restkit 0.20的iOS应用程序。主视图控制器是一个集合视图,它由使用Restkit的服务器请求填充。对服务器的请求返回要放置在每个单元中的图像和标题。如果用户选择了一个单元,我需要向服务器发出第二个请求,以获取有关所选单元的详细信息。

我在晚上尝试用prepareForSegue方法完成此操作。问题是我似乎无法弄清楚如何从prepareForSegue中的请求中获取结果。

以下是prepareForSegue方法

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"newsDetail"]) {

// I USE THIS PORTION TO GET DATA THAT IS NEEDED FOR THE GET REQUEST TO THE SERVER AND TO PASS SOME ADDITIONAL ITEMS FROM THE FIRST REQUEST TO THE DETAIL VIEW CONTROLLER
        NSIndexPath *indexPath = [[self.collectionView indexPathsForSelectedItems] lastObject];
        NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
        NSString *articleID =[object valueForKey:@"gistID"];
        NSString *personID = [object valueForKey:@"userID"];

// I USE THIS LINE TO ASSEMBLE THE STRING FOR getObjectsAtPath BELOW
        NSString *getArticle =[NSString stringWithFormat:@"/rest/article/getArticleForView?aid=%@&pid=%@&ip=255.255.255.0",articleID,personID];

//HERE I MAKE THE CALL TO THE SERVER USING RESTKIT METHODS        
        [[RKObjectManager sharedManager] getObjectsAtPath:getArticle parameters:nil success:nil failure:nil];    

        [[segue destinationViewController] setDetailItem:object];
    }
}

以下是我在详细视图控制器中加载它的方法。

- (void)configureView
{
    if (self.detailItem) {
        self.newsDetailText.text = [[self.detailItem valueForKey:@"fullArticle"]description];
        NSURL *photoURL =[NSURL URLWithString:[self.detailItem valueForKey:@"imageUrl"]];
        NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
        self.newsDetailImageView.image =[UIImage imageWithData:photoData];
    }
}

它将正确分割,并且将加载图像(已经从第一个请求持久化),但文本(从segue请求中检索到的)不会。实际上valueForKey fullArticle为空。

很明显,我是一个基于这个问题的新秀。考虑到这一点,代码片段非常有用。谢谢!

1 个答案:

答案 0 :(得分:0)

由于您正在执行异步请求,因此您想要显示的数据是在destinationViewController实际出现后到达的。因此,您应该将success块传递给您的请求并更新其中的视图。像这样:

UIViewController *viewController = [segue destinationViewController];
[[RKObjectManager sharedManager] getObjectsAtPath:getArticle parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    if (!operation.error) {
        viewController.newsDetailText.text = mappingResult.firstObject[@"fullArticle"];
    }
} failure:nil];