将JSON字符串从一个视图传递到另一个视图

时间:2014-01-11 17:12:06

标签: ios json parsing uitableview

我有一个表视图,我在其中解析一些JSON数据并将其显示在自定义单元格中。在一个视图中,我正在解析来自Facebook的特定用户的帖子。

我在表格视图中显示预览,但我想将数据传递到另一个视图。例如,我在表格视图中阅读了帖子的预览,但我想阅读整篇文章。

当我点击该帖子(单元格)时,我应该被定向到一个新的视图控制器,其中显示完整的帖子(在标签或文本视图中)。

我该怎么做?

这是我将数据解析到表视图的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    strURLToLoad = [[NSMutableString alloc] init];

    [btnFaceBook setTitle:@"link.com/json.php?name=Name" forState:UIControlStateDisabled];
    [btnTwitter setTitle:@"link1.com/json.php?name=Name" forState:UIControlStateDisabled];
    [btnTwitter2 setTitle:@"link2.com/json.php?name=Name" forState:UIControlStateDisabled];

    [btnFaceBook setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnFaceBook setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];

    [btnTwitter setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnTwitter setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];

    [btnTwitter2 setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnTwitter2 setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];



    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
    PostsObject *cell = [nib objectAtIndex:0];
    fontForCellText = cell.title.font;
    cellTextWidth = cell.title.frame.size.width;
    cellHeightExceptText = cell.frame.size.height - cell.title.frame.size.height;

    [self.navigationController setNavigationBarHidden:YES];

    self.tableView.separatorColor = [UIColor clearColor];

    // Setting Up Activity Indicator View
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityIndicatorView.hidesWhenStopped = YES;
    self.activityIndicatorView.center = self.view.center;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    self.tableView.separatorColor = [UIColor clearColor];

    // Initializing Data Source
    movies = [[NSMutableArray alloc] init];

    [self btnFromTabBarClicked:btnFaceBook];
}

- (void)loadJSONFromCurrentURL
{
    [self.activityIndicatorView startAnimating];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURLToLoad]];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [movies setArray:JSON];
        [self.activityIndicatorView stopAnimating];
        [self.tableView reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation start];
}

- (IBAction)btnFromTabBarClicked:(UIButton *)sender
{
    //Unselect all 3 buttons
    btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;

    //Select the button that was clicked
    sender.selected = YES;

    //Set the string of an NSMutableString property called strURLToLoad with the URL
    //The URL is pre stored in the text of the UIButton in the Disabled text.
    [strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];

    //Load the URL
    [self loadJSONFromCurrentURL];
}

// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (movies && movies.count) {
        return movies.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIdentifier = @"PostsObject";

    PostsObject *cell = (PostsObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    NSString *strText = [movie objectForKey:[self getTextKey]];

    CGRect rect = cell.title.frame;
    rect.size.height = [self getHeightForText:strText];
    cell.title.frame = rect;
    cell.title.text = strText;
    cell.arrow.center = CGPointMake(cell.arrow.frame.origin.x, rect.origin.y + rect.size.height/2);
    cell.published.text = [movie objectForKey:@"published"];
    cell.twitterName.text = [movie objectForKey:[self getTwitterName]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    NSString *strText = [movie objectForKey:[self getTextKey]];

    CGFloat cellHeight = cellHeightExceptText + [self getHeightForText:strText];

    return cellHeight;
}

- (NSString *)getTextKey
{
    return btnTwitter.selected?@"tweet":@"message";
}

- (NSString *)getTwitterName
{
    return btnTwitter2.selected?@"user":@"user";
}

- (CGFloat)getHeightForText:(NSString *)strText
{
    CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
    CGSize labelSize = [strText sizeWithFont:fontForCellText constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    NSLog(@"labelSize.height = %f",labelSize.height);
    return labelSize.height;
}

2 个答案:

答案 0 :(得分:1)

有很多方法可以实现这一目标。

您可以实现tableview:didSelectRowAtIndexPath:并在其中,分配下一个VC并将您的数据传递给其属性,然后呈现该VC。

或者您可以实现从表格单元格到新VC的segue,然后在prepareForSegue:中将数据传递给其属性。

无论哪种方式,所呈现的VC都可以通过viewDidLoad将数据加载到tis视图中。

就传递JSON而言,它并不是特别优化。您可以考虑创建自己的基于Objective-c的模型对象,将JSON数据解析为,并在应用程序中使用这些模型对象。

答案 1 :(得分:0)

您可以使用自己的init方法将所需的相应数据传递给下一个视图控制器。为了向您展示这一点,我创建了一个名为NextViewController的新视图控制器,并编写了我自己的自定义init方法,该方法将字典作为参数。我将此函数添加到头文件中,以便原始视图控制器可以访问它,并将字典作为属性添加,以便您可以在各种函数中的整个文件中访问它(实例变量也可以工作),导入将NextViewController的.h文件放入我的原始表视图的文件中,并在tableView的didSelectRowAtIndexPath函数中从数据源数组中获取基于indexPath的所选对象,在你的案例电影中,并创建了一个NextViewController实例,通过它的init函数传入该字典。以下是相关代码:

NextViewController的.h文件

@interface NextViewController : UIViewController

- (id)initWithDictionary:(NSDictionary *)dictionary;

@property (nonatomic, retain) NSDictionary *myDictionary;

@end

NextViewController的.m文件:

@interface NextViewController ()

@end

@implementation NextViewController

- (id)initWithDictionary:(NSDictionary *)dictionary {
    self = [super initWithNibName:nil bundle:nil];

    self.myDictionary = dictionary;

    return self;
}

@end

在原始tableViewController中:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // first deselect the cell so it doesn't stay highlighted
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // then grab the json you want to pass from your tableView's datasource
    NSDictionary *selectedMovie = self.movies[indexPath.row];

    // create the nextViewController and pass in the appropriate dictionary to it
    NextViewController *nextVC = [[NextViewController alloc] initWithDictionary:selectedMovie];

    // then tell our navigation controller to push this new controller onto the view stack
    [self.navigationController pushViewController:nextVC animated:YES];
}

如果这有帮助,或者您需要进一步澄清,请告诉我。