【问题标题】:Load huge data from multiple urls and then show it in the view从多个 url 加载大量数据,然后在视图中显示
【发布时间】:2012-07-27 07:34:15
【问题描述】:

我正在开发一个 iPhone 应用程序。在应用程序中,我需要从 Web 加载大量数据 (JSON),然后相应地创建视图。请建议我如何进行。

基本上我在做的是

1.从数组中加载一个 json 的 web 服务。

2。上面收到的数组包含指向其他 Web 服务的 URL。比方说,8

3.所以现在我需要调用 8 个网络服务,在获取之后,我必须解析数据,然后将其显示给用户。

这是我第一次处理网络服务。所以不知道该怎么做。

主要问题是时间消耗。如何在其中实现多线程?

请提出任何可以帮助我的想法或链接。

【问题讨论】:

    标签: ios iphone multithreading web-services load


    【解决方案1】:

    我会做什么:

    1. 创建一个新的NSThread 和对应的@autoreleasepool 来加载第一个json
    2. 加载“主要 JSON”数据后:将所有 url 放入 NSMutableArray
    3. 加载上述数组的第一个 URL(同样在同一个线程中)的 JSON 日期
    4. 加载 JSON 数据后,存储 JSON 数据
    5. 从您在 [2] 中创建的数组中删除第一个元素。
    6. 如果您的数组不为空 > 转到第 3 步。

    这样的? (没有测试过):

    #import "JSONKit.h"
    - (void)viewDidLoad {
        [super viewDidLoad];    
        [NSThread detachNewThreadSelector:@selector(_loadJSON) toTarget:self withObject:nil];
    };
    
    -(void)_startNewThread {
        @autoreleasepool {
            NSError *error = nil;
            /*
             main json file:
             [
                 { "url": "http://domain.com/file2.json" },
                 { "url": "http://domain2.com/file.json" },
                 { "url": "http://domain3.com/file.json" }
            ]
        */   
        NSMutableArray *mainUrls = [[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://domain.com/file.json"] encoding:NSUTF8StringEncoding error:&error] mutableObjectFromJSONString];
        NSMutableArray *returnArray = [[NSMutableArray alloc] init];
        if (error == nil) {
            while ([mainUrls count]) {
                NSURL *url = [NSURL URLWithString:[[mainUrls objectAtIndex:0] objectForKey:@"url"]];
                NSDictionary *dictionary = [[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error] objectFromJSONString];
                if (error == nil) {
                    [returnArray addObject:dictionary];
                }
                [mainUrls removeObjectAtIndex:0];
            }
        }
        [returnArray autorelease];
        [self performSelectorOnMainThread:@selector(_finished:) withObject:[NSArray arrayWithArray:returnArray] waitUntilDone:YES];
        }
    }
    
    -(void)_finished:(NSArray *)__array {
        NSLog(@"Result: %@", __array);
    }
    

    【讨论】:

    • 非常感谢@basvk。它看起来很糟糕。我可以有一些描述的想法的代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2012-04-23
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多