2012-06-20 67 views
0

我想加载json到一个uitableview。我曾与json工作过,但从未用过tableview。我不断收到此错误: - [__ NSCFNumber count]:无法识别的选择器发送到实例。我很确定这是因为在numberOfRowsInSection方法中,我返回数组的数量。请让我知道如何解决这个问题,或者如果我错过了一些东西而没有看到它。加载Json到uitableview

这里是他的代码: .h文件中

@interface HistoryViewController : UITableViewController <UITableViewDataSource,     UITableViewDelegate> 
{ 
    NSArray *jsonData; 
    NSMutableData *responseData; 
} 

.m文件

- (void)viewDidLoad 
{  
responseData = [[NSMutableData data] retain]; 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"Json url"]]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self ]; 


[super viewDidLoad]; 
} 


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
[responseData setLength:0]; 
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
[responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
NSLog(@"Connection failed: %@", [error description]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
[connection release]; 

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
[responseData release]; 

NSDictionary *dictionary = [responseString JSONValue]; 
NSArray *response = [dictionary objectForKey:@"name"]; 

jsonData = [[NSArray alloc] initWithArray:response]; 
} 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
return jsonData.count; 
} 

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

UITableViewCell *cell = [[UITableViewCell alloc] 
         initWithStyle:UITableViewCellStyleDefault 
         reuseIdentifier:@"cell"]; 


cell.textLabel.text = [jsonData objectAtIndex:indexPath.row]; 

return cell; 
} 
+0

我猜的是'[dictionary objectForKey:@“name”]'实际上是返回一个数字,而不是像你的代码所期望的数组。你可以放置一行'NSLog(@“Key:%@”,[dictionary objectForKey:@“name”])''或类似的东西,并告诉我们返回什么?这将允许我们确定该字典键中的数据类型。 –

+0

您应该使用AFNetwork + JSONKit,并使用AFJsonRequestOperation,它更简单! – Cyrille

+0

@Paul我插入NSLog并返回数组 – Sean

回答

1

好吧,我注意到你的数组初始化从未直到connectionDidFinishLoading方法运行。您的数据表的代表方法可能在connectionDidFinishLoading之前运行,因此您应该初始化您的jsonData阵列viewDidLoad而不是connectionDidFinishLoading

你可以把你的connectionDidFinishLoading调用相同的,但要确保你在connectionDidFinishLoading方法结束您的数据表调用reloadData填写您的数据表下载的数据。

+0

谢谢你的工作! – Sean