转换一行代码以与XCode 4.2中的故事板兼容

时间:2012-02-29 19:13:41

标签: objective-c ios xcode xcode4.2 storyboard

我有一个rss解析器,我正在转换为故事板格式,我遇到了一个问题。当用户触摸具有rss feed的表视图的一部分时,它会使用以下代码将视图推送到详细视图控制器:

- (id)initWithItem:(NSDictionary *)theItem {
if (self == [super initWithNibName:@"RssDetailController" bundle:nil]) {
    self.item = theItem;
    self.title = [item objectForKey:@"title"];
}

return self;
}

当我运行它时,它工作正常,但当我试图看故事时崩溃。显然这是因为我不再使用任何笔尖因为使用了故事板,但是如何更改代码才能工作呢?

很抱歉,如果我的措辞不好。如果您有任何问题或需要澄清,我会在评论中回答

1 个答案:

答案 0 :(得分:1)

不是尝试使用详细视图控制器的自定义init方法设置属性值,而是使用表视图控制器的prepareForSegue:方法在故事板范例下处理此问题的更好方法

如果在tableview控制器中设置故事板中的segue到详细视图控制器,则会在segue发生时调用此方法。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{           
    if ([segue.identifier isEqualToString:@"ShowDetail"]) {  // be sure to name your segue in storyboard

        // sender in this case is the tableview cell that was selected
        UITableViewCell *cell = sender;

        // get the index path for the selected cell
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

        // use the indexPath to get the appropriate item from your data source
        NSDictionary *theItem = [self.dataArray objectAtIndex:[indexPath row]];  // or whatever

        // get the view controller you are about to segue to
        RssDetailController *rssDetailvc = [segue destinationViewController];

        // set the properties
        rssDetailvc.item = theItem;
        rssDetailvc.title = [theItem objectForKey:@"title"];
    }
}