0

我正在尝试将 json 加载到 uitableview 中。我以前使用过 json,但从未将它与 tableview 一起使用。我不断收到此错误:-[__NSCFNumber count]: unrecognized selector sent to instance。我很确定这是因为在 numberOfRowsInSection 方法中我返回了数组的计数。请让我知道如何解决这个问题,或者我是否遗漏了某些东西而没有看到它。

这是他的代码:.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;
}
4

1 回答 1

1

好吧,我注意到你的数组在connectionDidFinishLoading方法运行之前永远不会初始化。您的数据表的委托方法可能之前运行过connectionDidFinishLoading,因此您应该初始化您的jsonData数组viewDidLoad而不是connectionDidFinishLoading.

You can keep your connectionDidFinishLoading calls the same, but make sure you call reloadData on your data table at the end of the connectionDidFinishLoading method to fill out your data table with the downloaded data.

于 2012-06-20T15:47:13.527 回答