使用indexpath.row来引用从JSON对象数组中获取对象

时间:2013-12-04 10:12:42

标签: ios objective-c json uitableview

亲爱的StackOverflow用户,

First Post所以会尽我所能!

我有一个简单的JSON文件,看起来像这样(我不会包含所有内容,因为它太长了):

{
"guidelines": [
{
  "title": "Editorial - Doporučené postupy",
  "guidelinepath": "1 - Editorial"
},
{
  "title": "Preambule",
  "guidelinepath": "1 - Preambule"
},
{
  "title": "Zásady dispenzární péče ve fyziologickém těhotenství",
  "guidelinepath": "1- Z"
},
{
  "title": "Provádění screeningu poruch glukózové tolerance v graviditě",
  "guidelinepath": "2"
}]
}

有了这些数据,我设法填充了一个tableView(也就是说,在命令行输出中正确解析了JSON),为我欢呼。现在我想做的是检测已被点击并直接指向与该标题相关的指南路径JSON对象的tableView单元格(这将导致文本文件将填充文本视图)。我试过了许多不同的解决方案,但它们导致了(null)。

以下是我设法完成的不完整代码,它没有错误。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"showGuideline"]) {
    NSLog(@"seguehasbeenselected");
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSLog(@"%@ is the indexpath", indexPath);
}
}

我试图彻底研究这个问题并试图帮助自己解决以下问题: Using indexPath.row to get an object from an array

getting json object and then assign to uitable view

但他们无法以某种方式真正回答我的问题。非常感谢任何帮助!

对于那些想要获得有关如何解析JSON的更多信息的人,以下是代码:

{
[super viewDidLoad];
NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"postupy" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(@"%@",dataDictionary);
self.guidelines = [dataDictionary objectForKey:@"guidelines"];
self.guidelineFiles = [dataDictionary objectForKey:@"guidelinepath"];
}

指南声明文件和指南:

#import <UIKit/UIKit.h>


@interface PostupyTableViewController : UITableViewController

@property (nonatomic, strong) NSArray *guidelines;
@property (nonatomic, strong) NSArray *guidelineFiles;


@end

- 最终解决方案 -

我按如下方式编辑了prepareForSegue方法,现在它完美无缺:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{
    if ([segue.identifier isEqualToString:@"showGuideline"]) {
        NSLog(@"seguehasbeenselected");
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSLog(@"%@ is the indexpath", indexPath);
        NSDictionary *item = [self.guidelines objectAtIndex:indexPath.row];
        NSString * path = [item objectForKey :@"guidelinepath"];
        NSLog(@"%@ is the path",path);
        PostupyDetailViewController *pdwc = (PostupyDetailViewController *)segue.destinationViewController;
        pdwc.guidelineChosen = path;
    }
}

1 个答案:

答案 0 :(得分:1)

从你的json看来[dataDictionary objectForKey:@"guidelines"];返回一个NSArray。因此,访问正确的项目只需使用:

NSDictionary *item = [self.guidelines objectAtIndex:indexPath.row];
NSString     *path = [item objectForKey:@"guidelinepath"];