2013-08-06 30 views
0

我有一个问题。我从我的URL得到的JSON它看起来像这样:Objective-C JSON到TableView非常慢

- (NSMutableArray *)parseObject:(NSString *)object withKey:(NSInteger)key { 
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults]; 
NSString *randomKey = [standardUserDefaults stringForKey:@"randomKey"]; 

NSString *urlString = [NSString stringWithFormat:@"http://domain.com"]; 
NSURL *url = [NSURL URLWithString:urlString]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
NSError *error; 
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

NSArray* latestLoans = [json objectForKey:@"object"]; 
NSDictionary* loan = [latestLoans objectAtIndex:key]; 

NSArray *myWords = [[loan objectForKey:object] componentsSeparatedByString:@","]; 

return myWords; 
} 

为了我的TableView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
} 

cell.textLabel.text = [[self parseObject:@"bedrijfsnaam" withKey:0] objectAtIndex:indexPath.row]; 
//cell.detailTextLabel.text = [[self parseObject:@"leverunix" withKey:0] objectAtIndex:indexPath.row]; 
cell.textLabel.font = [UIFont systemFontOfSize:14.0]; 
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; 
cell.textLabel.numberOfLines = 3; 
cell.selectionStyle = UITableViewCellSelectionStyleNone; 
return cell; 
} 

它加载真的慢,我有一种滞后的,当我想滚动。我能做些什么来改善这一点?

感谢

回答

3

看来你从每个是cellForRowAtIndexPath被调用时服务器获取JSON数据。这一定很慢!

您应该只有一次(例如,在viewDidLoad)获取数据,反序列化JSON 并将结果存储在视图控制器的某些属性,使cellForRowAtIndexPath可以从那里得到的对象。

+0

我有一个viewDidLoad中的数组,并把我的所有数据放在该数组中,它现在工作完美。谢谢 –

+0

更一般地说,你正在对主线程执行阻塞操作,这意味着在接收并分析JSON响应之前不会创建单元。如果服务器需要30秒才能响应,您的应用将在30秒内无响应! –

+0

@HenkdeBoer:不客气。 - 但也看看timthetoolman的答案。即使是单个URL请求也可能需要很长时间,所以异步获取数据(或在后台线程中)以避免主UI被阻止也是很好的建议。 –

0

您在的cellForRowAtIndexPath一再呼吁

- (NSMutableArray *)parseObject:(NSString *)object withKey:(NSInteger)key 

这不应该发生。

尝试在viewDidLoad或viewWillAppear中获取数据,然后将该数据保存到全局变量中。

现在调用将从该变量获取数据并返回所需值的任何函数。

+0

全局变量? –

+0

本地任何类变量 –

2

您对

NSData *data = [NSData dataWithContentsOfURL:url]; 

调用导致主线程它是从该网页的网址检索数据而阻塞。

尝试使用异步方法。它会解决问题。

+0

感谢它非常有帮助。 –