使用prepareforSegue来DetailViewController

时间:2014-02-21 11:03:01

标签: ios objective-c segue uistoryboardsegue

我在使用prepareForSegue方法来推送DetailViewController时遇到了问题。

我一直在关注很多教程,但是当我想使用自己的数据时,我显然没有做正确的事情。

我的tableView加载了这段代码,然后我想在用户选择博客帖子时传递给detailviewcontroller。

NSURL *blogURL = [NSURL URLWithString:@"http://theforeground.co.uk/feed/json"];

NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];

NSError *error = nil;

self.blogPosts = [NSMutableArray array];
NSArray *blogPostsArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];


for (NSDictionary *bpdictionary in blogPostsArray) {
    BlogPost * blogPost = [BlogPost blogPostWithTitle:[bpdictionary
        objectForKey:@"title"]];
    blogPost.excerpt = [bpdictionary objectForKey:@"excerpt"];
    blogPost.thumbnail = [bpdictionary objectForKey:@"thumbnail"];
    blogPost.date = [bpdictionary objectForKey:@"date"];
    blogPost.content = [bpdictionary objectForKey:@"content"];
    [self.blogPosts addObject:blogPost];
}

我有一个从tableviewcell到detailviewcontroller的segue,并称之为“ShowDetailView”,这是我正在使用的prepareForeSegue方法

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"ShowDetailView"])
    {
        DetailViewController *detailViewController = [segue destinationViewController];
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        BlogPost *blogPost = [self.blogPosts objectAtIndex:indexPath.row];

    }

我已将“detailviewcontroller.h”导入“tableviewcontroller.m”,我在detailviewcontroller头文件中有这些属性

@property (nonatomic, strong) NSMutableArray *blogPosts;
@property (weak,nonatomic) IBOutlet NSString *blogTitle;

请有人帮助这个初学者。感谢

1 个答案:

答案 0 :(得分:1)

您从数据源检索数据但未将其传递给视图控制器,请尝试:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"ShowDetailView"])
    {
        DetailViewController *detailViewController = [segue destinationViewController];
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        BlogPost *blogPost = [self.blogPosts objectAtIndex:indexPath.row];

        // You passing the data here to detail view controller
        detailViewController.blogPost = blogPost;

    }
}

您还需要将blogPost属性添加到detailviewcontroller.h文件中:

@property (nonatomic, strong) BlogPost *blogPost;

之后你可以使用它,例如在detailviewcontroller.m文件中的viewDidLoad方法中。