JSON显示文本 - 冻结UI

时间:2011-02-10 06:54:48

标签: iphone json sdk

我目前有一个非常简单的视图,它显示来自JSON提要的信息。我面临的问题是,当我按下此选项卡时,我遇到的几秒钟暂停。如何让这个视图立即加载,然后加载label.text区域?优先考虑活动指标?

我应该使用线程吗?

提前致谢!

代码:

- (NSString *)stringWithUrl:(NSURL *)url {
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:30];
    NSData *urlData;
    NSURLResponse *response;
    NSError *error;

    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
    }


- (id)objectWithUrl:(NSURL *)url {
    SBJsonParser *jsonParser = [SBJsonParser new];
    NSString *jsonString = [self stringWithUrl:url];
    return [jsonParser objectWithString:jsonString error:NULL];
    }


- (NSDictionary *)downloadStats {
    id response = [self objectWithUrl:[NSURL URLWithString:@"http://www.example.com/JSON"]];
    NSDictionary *feed = (NSDictionary *)response;
    return feed;
    [feed release];
    }

- (void)viewDidLoad {
    [super viewDidLoad];

    [GlobalStatsScrollView setScrollEnabled:YES];
    [GlobalStatsScrollView setContentSize:CGSizeMake(320, 360)];
}

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"View appears");

    // Download JSON Feed
    NSDictionary *feed = [self downloadStats];      
    totalproduced.text = [feed valueForKey:@"Produced"];
    totalno.text = [feed valueForKey:@"Total"];
    mostcommon.text = [feed valueForKey:@"Most Common"];
    }

2 个答案:

答案 0 :(得分:1)

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"View appears");

    UIActivityIndicatorView* spiner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhiteLarge];
    spiner.tag = 123;
    [self.view addSubview: spiner];
    [spiner startAnimating];
    [spiner release];

    NSThread* thread = [[NSThread alloc] initWithTarget: self 
                                               selector: @selector(loadFeed) object: nil];
    [thread start];

}

-(void) loadFeed {
    // Download JSON Feed
    NSDictionary *feed = [self downloadStats];      
    totalproduced.text = [feed valueForKey:@"Produced"];
    totalno.text = [feed valueForKey:@"Total"];
    mostcommon.text = [feed valueForKey:@"Most Common"];

    [[self.view viewWithTag: 123] removeFromSuperview];
}

不要忘记之后释放你的帖子。 您还应该检查NSOperationQueue的文档

另一种选择是使用异步请求。

答案 1 :(得分:1)

问题是-[NSURLConnection sendSynchronousRequest:]阻塞,直到它拥有所有数据。

解决此问题的最佳方法是实现异步请求(请阅读NSURLConnection有关如何执行此操作的参考信息。)

你也可以在像Max建议的后台线程中进行同步连接,不过我建议使用performSelectorInBackground:而不是手动创建线程。无论哪种方式,不要忘记首先在新线程中设置NSAutoreleasePool以避免泄漏,并且还要注意调用GUI方法(如设置UILabel的文本)需要在主线程上完成,例如使用{ {1}}。正如您所看到的,线程版本存在一些缺陷,因此我建议实现异步连接。