我想加载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;
}
我猜的是'[dictionary objectForKey:@“name”]'实际上是返回一个数字,而不是像你的代码所期望的数组。你可以放置一行'NSLog(@“Key:%@”,[dictionary objectForKey:@“name”])''或类似的东西,并告诉我们返回什么?这将允许我们确定该字典键中的数据类型。 –
您应该使用AFNetwork + JSONKit,并使用AFJsonRequestOperation,它更简单! – Cyrille
@Paul我插入NSLog并返回数组 – Sean