读取每个视图的JSON数据

时间:2012-09-27 14:09:37

标签: objective-c ios json

我是iOS开发的新手,正在编写一个包含多个视图的应用程序,每个视图都有一个tableview。

对于每个视图,我需要读取单独的JSON URL,然后显示结果。我一直在检查的所有教程都在ViewController.m中读取数据,但由于每个视图都有一个单独的URL,我可以将代码概括并在其他地方编写吗?

另外,我想把它放在数据加载最有效的地方,即点击按钮时我的应用程序没有太多等待时间。

我使用以下链接作为参考:http://www.raywenderlich.com/5492/working-with-json-in-ios-5

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以创建单独的解析器,模型类来解析单独的json url。然后在每个视图加载中加载已解析的数据。

答案 1 :(得分:0)

我建议你有一个单独的解析器类iTemplateParser

然后在其他View Controller中,您可以创建iTemplateParser对象。

@property (nonatomic, strong) iTemplateParser *templateData;

- (void)viewDidLoad {

    NSData *theData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:templateFileName ofType:@"json"]];
    self.templateData = [[iTemplateParser alloc] initWithTemplateData:[NSJSONSerialization JSONObjectWithData:theData options:NSJSONReadingMutableContainers error:nil]];
}

现在在iTemplateParser,您可以根据需要定义许多功能。 E.g。

- (id)initWithTemplateData:(NSDictionary *)iDataDict;
- (CGRect)frameForTableView;
- (UIFont *)fontForTableView;
- (UIColor *)tableBackgroudColor;

现在,您可以在ViewController中调用此方法来显示UI组件。

希望这会对您有所帮助。