【发布时间】:2016-11-06 20:47:12
【问题描述】:
我一直在尝试将来自网络服务器的 JSON 数据附加到 tableviewcontroller 中。这是我当前的代码。
_datalist 的 NSlog 打印 JSON,但实际将数据放入单元格的其他方法没有。代码看起来正确,并且由于 _datalist NSarray 实际获取数据,我不确定如何处理这..这就是为什么我需要你的帮助和建议。
至于我发现的,用 JSON 数据初始化单元格的方法,既不能获取它,也不能使用它。我的线索是我需要对传入的数据进行编码?
#import "TopUsersViewController.h"
@interface TopUsersViewController ()
@property NSArray* dataList;
@end
@implementation TopUsersViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self readDataFromFile];
[self.tableView reloadData];
}
-(void)readDataFromFile
{
NSString *urlAsString = @"http://myURL.com/json.json";
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSLog(@"%@", urlAsString);
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (error)
{
// no internet / can't fetch!
NSLog(@"Failure %@",error.localizedDescription);
}
NSLog(@"Success!");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"works.");
self.dataList = (NSArray *)[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
// this NSlog prints the JSON data successfully.
NSLog(@"oo%@ and array %@",_dataList,_array);
});
}];
}
// 这些方法都没有运行..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// count the initialized array from viewDidLoad
return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"return the data");
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
id keyValuePair = self.dataList[indexPath.row];
cell.textLabel.text = keyValuePair[@"identity"];
cell.detailTextLabel.text=[NSString stringWithFormat:@"Points: %@", keyValuePair[@"points"]];
return cell;
}
@end
【问题讨论】:
-
下次我会更仔细地查看其他问题,谢谢您指出这一点!编码愉快!
-
@SyedeHussaini 如果您要向其他人指出问题,您确实需要解决您的答案中的问题。
-
另外,您的链接是针对 Swift 的。由于我当前的应用程序是用 Obj-c 编写的,因此不相关。 :P
标签: ios objective-c json uitableview