我一直在嘗試從Web服務器將JSON數據附加到tableviewcontroller中。這是我現在的代碼。JSON到Tableview
_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如果你要指出其他人,你真的需要解決你的答案中的問題。 – rmaddy
另外,你的鏈接是Swift。由於我目前的應用程序是用Obj-c編寫的,因此它不相關。 :P –