【发布时间】:2014-03-07 02:13:52
【问题描述】:
我有一个简单的 JSON 提要,我可以在控制台中解析和查看它,但我似乎无法让它显示在我的表格视图中。我正在使用 Xcode 5.0.2。我不确定为什么当回显到控制台时我可以在 for 循环中看到它,但在表格视图中却看不到。
仅供参考,我是在 xcode 和目标 c 中构建的新手,我使用这个 video tutorial 作为指南。
我的 Json 看起来像这样:
[ { "first_name": "比尔" }, { “名字”:“泰德” }, { “名字”:“乔治” } 等等... ]PhotoTableViewController.h
#进口 #import "DisplayViewController.h" @interface PhotosTableViewController : UITableViewController { IBOutlet UITableView *mainTableView; NSArray *新闻; NSMutableData *数据; } @结尾PhotoTableViewController.m
@interface PhotosTableViewController () { NSMutableArray *照片; NSArray *_locations; } - (void)viewDidLoad { NSURL *url = [NSURL URLWithString:@"http://feedurl.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } // 为简洁起见省略了一些代码 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // 返回部分的数量。 返回 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 返回节中的行数。 //返回照片.count; NSLog(@"新闻计数:%lu", news.count); 返回 news.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 静态 NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; cell.textLabel.text = [[照片 objectAtIndex:indexPath.row] objectForKey:@"first_name"]; NSLog(@"anything: %@", [[照片 objectAtIndex:indexPath.row] objectForKey:@"first_name"] ); 返回单元格; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 数据 = [[NSMutableData alloc] 初始化]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData { [数据追加数据:数据]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 新闻 = [NSJSONSerialization JSONObjectWithData:数据选项:0 错误:无]; NSDictionary *first_name; for (int i=0; i (这里不能放小于号会破坏代码视图) [news count] i++) { first_name = [news objectAtIndex:i]; NSLog(@"状态:%@", [first_name objectForKey:@"first_name"]); } [mainTableView 重载数据]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"下载无法完成 - 请确保您已连接到互联网。" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; [错误视图显示]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }【问题讨论】:
-
乍一看,您的代码看起来还不错。你说你可以在控制台看到 NSLog 输出——你也能看到这个:news count: N?
-
没有新闻计数为 0,我可以在 connectionDidFinishLoading 区域内看到计数,但在其他地方看不到,它确实在那里得到计数。
-
你告诉mainTableView谁是delegate和datasource吗?
-
我相信是这样,但有什么方法可以验证这一点吗?是在 pPhotoTableViewController.h 文件中吗?
-
通常你应该找到像 mainTableView.dataSource = ... 这样的行,如果它是在代码中完成的。或者您应该在界面生成器中的表格视图的 Outlets 中找到它。