使用JSON和AFNetworking NSDictionary使用数据填充tableview [英] populating a tableview with data using JSON and AFNetworking NSDictionary

查看:98
本文介绍了使用JSON和AFNetworking NSDictionary使用数据填充tableview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c& ios n00b在这里,

c & ios n00b here,

我已经解决了这个问题3天了。我担心我缺少一个基本概念。我已经研究并完成了与此相关的每个教程和堆栈溢出问题,我无法得到答案。我试图用json文件中的数据填充我的tableviewcontroller。我可以从JSON文件连接和输出,但我似乎无法解析字典并实际使用字典。以下是我认为最接近正确的代码:

I have been working on this problem for 3 days. I am worried that there is a fundamental concept that I am missing. I have researched and and done every tutorial and stack overflow question that relates to this and I can't get an answer. I am trying to populate my tableviewcontroller with data from a json file. I can connect and output from the JSON file but I cannot seem to parse the dictionary and actually use the dictionary. Here is my code that I think is closest to getting it right:

TABLEVIEW CONTROLLER
#import "AllTableViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "Beer.h"


@interface AllTableViewController ()

@end

@implementation AllTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    NSURL *URL = [NSURL URLWithString:@"http://www.hopshack.com/db_get_all_beer.php"];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject[@"beer"][3][@"name"]);
       NSMutableArray *tempArray=[[NSMutableArray alloc]init];
        for(NSDictionary *oneDictionary in responseObject){
            Beer *newBeer=[[Beer alloc]initWithName:oneDictionary[@"beer"][@"name"]];
            [tempArray addObject:newBeer];
        }
        self.beers=[[NSArray alloc]initWithArray:tempArray];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Beer"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];
    [operation start];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.beers.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pCell" forIndexPath:indexPath];

    if(cell==nil){
        cell=[[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"pCell"];
    }
    cell.textLabel.text=[self.beers[indexPath.row] name];
    return cell;
}
BEER MODEL
#import "Beer.h"
#import "AFHTTPRequestOperation.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"

@implementation Beer
-(id)initWithName:(NSString *)aName{
    self=[super init];
    if(self){
        self.name=aName;
    }
    return self;
}

@end

非常感谢你们提前您的帮助。这个网站规则。

Thanks so much guys in advance for your help. this site rules.

推荐答案

如果您 self.beers 数组已正确填充,则我认为你没有重新加载tableview。

If you're self.beers array is properly populated then I think you are not reloading the tableview.

self.beers = [[NSArray alloc] initWithArray:tempArray]之后添加这一行;

dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData]
            });

收到所有数据后,它会重新加载tableview。
如果这不起作用,则 NSLog(@%@,self.beers); 以确保自我。啤酒被填充。

It will reload the tableview after you receive all the data. If that doesn't work then NSLog(@"%@",self.beers); to make sure that self. beers is populated.

我没有意识到在实际填充tableView之前它给你一个错误。我认为问题是名称返回 NSString 而不是 NSArray 。实际上,responseObject包含字典数组,因此当您遍历数组时,您会获得每个啤酒的字典。通过这种方式,您只需使用 objectForKey

I didn't realize it is giving you an error before actually populating the tableView. I think the problem is that the name is returning a NSString and not an NSArray. Actually the responseObject contains array of dictionaries so that when you iterate through the array you get a dictionary for each beer. This way you can just access the beer name with objectForKey

Beer *newBeer=[[Beer alloc]initWithName:[oneDictionary objectForKey@"name"]];

检索啤酒的名称。

让我知道它是否成功。

这篇关于使用JSON和AFNetworking NSDictionary使用数据填充tableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆