【问题标题】:How populate prototype cell text labels with NSDictionary object populated with JSON data using AFNetworking如何使用 AFNetworking 填充带有 JSON 数据的 NSDictionary 对象来填充原型单元格文本标签
【发布时间】:2013-05-12 17:07:32
【问题描述】:

iOS 新手。我正在使用 AFNetworking 下载 JSON 数据并将数据放入 Dictionary 对象中。这是在以下代码中完成的:

-(void)locationRequest
{
NSURL *url = [NSURL URLWithString:@"http://sitespec/php/getlocations.php"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
//AFNetworking asynchronous url request
AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                     JSONRequestOperationWithRequest:request
                                     success:^(NSURLRequest *request, NSHTTPURLResponse         *response, id responseObject)
                                     {

                                         self.locationsFromJSON = (NSDictionary *)responseObject;

                                         NSLog(@"JSON RESULT %@", responseObject);
                                         NSLog(@"JSON DICTIONARY %@", _locationsFromJSON);
                                         [self.tableView reloadData];
                                     }
                                     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
                                     {
                                         NSLog(@"Request Failed: %@, %@", error, error.userInfo);
                                     }];

[operation start];

}

我正在获取数据并填充 Dictionary 数组,如下面的 NSLOG 调用的结果所示:

2013-05-12 12:44:08.851 sitespec[2024:c07] JSON RESULT (
    {
    city = "Rocky Mount";
    id = 1;
    name = "Rocky Mount";
    phone = "(252) 451-1811";
    state = NC;
    "street_address" = "620 Health Drive";
    zip = 27804;
},
    {
    city = "Elizabeth City";
    id = 2;
    name = "Elizabeth City";
    phone = "(252) 335-4355";
    state = NC;
    "street_address" = "109 Corporate Drive";
    zip = 27906;
}
)
2013-05-12 12:44:08.852 sitespec[2024:c07] JSON DICTIONARY (
    {
    city = "Rocky Mount";
    id = 1;
    name = "Rocky Mount";
    phone = "(252) 451-1811";
    state = NC;
    "street_address" = "620 Health Drive";
    zip = 27804;
},
    {
    city = "Elizabeth City";
    id = 2;
    name = "Elizabeth City";
    phone = "(252) 335-4355";
    state = NC;
    "street_address" = "109 Corporate Drive";
    zip = 27906;
}
)

但是,这里是我迷路的地方......

如何在我的字典对象中访问这些数据

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

方法?

类似:

 static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

cell.textLabel.text = [self.locationsFromJSON objectForKey:@"name"]; 

???

这不起作用,我收到一个 SIGBART 错误。我只是不知道如何读取数据并填充表格视图?

我该怎么做?非常感谢任何帮助.....

【问题讨论】:

    标签: ios json nsdictionary nstableview afnetworking


    【解决方案1】:

    我经常看到这种情况,但我不明白为什么人们很难从字典中提取数据并用字典的内容填充表格视图。我不明白为什么人们不为 JSON 响应创建模型类,然后根据需要将模型添加到数组中。

    所以 Tommy 我强烈建议您创建一个名为 Address 的类模型(例如)并将所有 JSON 属性作为属性添加到您的模型类中,当您解析 JSON 时,您会创建 Address 类实例您将添加到数组中。之后,在您的表格视图类中,您将有一个地址数组和用于:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section你会返回yourAddressesArray.count

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    Address *address = [yourAddressesArray objectAtIndex:indexPath.row];    //assign your address properties to labels etc 
    

    }

    拥有模型类会更容易 ;)

    编辑解析

    根据我在您的问题中看到的内容,您有一系列字典。所以我建议做这样的事情:

    在你的 Address 类中使用 josn 创建一个 imit 方法:

    -(id)initAddressWithJSON:(id)JSON {
        slef = [super init];
        if(self) {
          self.city = [JSON objectForKey:@"city"];
          // set all the properties here
        }
        return self;
    }
    

    当您收到调用的 json 响应时,比如说“jsonResopnse”,您应该执行以下操作:

    -(NSArray*)myAddressesFromJSON:(id)JSON {
    
       //you should add a validation here for JSON  (not null not empty)
       NSMutableArray *addresses = [[NSMutableArray alloc] init];
       Address *address;
       for(NSDictionary *addressDict in JSON) {
           address = [[Address alloc] initWithJSON:addressDict];
           [addresses addObject:address]; 
       }
       return addresses;
    }
    

    请注意,我是从脑海中编写代码,并没有使用 Xcode :) 并且可能存在一些构建错误(拼写错误),但我希望您明白这一点。另外我想你正在使用 JSONKit。

    【讨论】:

    • 我创建了一个地址模型并添加了我的 JSON 数据的所有属性。我已将 Address.h 文件导入到我的 tableView.m 文件中,我在其中下载数据并希望显示 tableView。我定义了一个名为 locationsFromJSON 的数组,按照您上面的指示进行操作。但是,一个后续问题,您说“当您解析 JSON 时,您会创建将添加到数组中的 Address 类实例”我在返回值中有 JSON 响应:responseObject。如何创建 Address 类实例并将它们添加到数组中?
    【解决方案2】:

    如我所见,您在同一类中使用 JSON 请求和 UITableView。在cellForRowAtIndexPath 方法中设置断点并检查是否已有数据。如果没有,那么:

    询问- (NSInteger)numberOfRowsInSection:(NSInteger)section 方法或已经在numberOfSections 询问您的字典是否已填满。否则返回 0。

    在您接收 JSON 数据的方法中调用 [tableView reloadData];

    如果这不是问题,请告诉您在哪里得到了 SIGBART 错误;)

    【讨论】:

      【解决方案3】:

      感谢 danypata 提供的出色反馈。我采取了稍微不同的路线来实现这一目标。让我想到的是 danypata 的评论“看起来你的 JSON 响应中有一个字典数组”......在 AFNetworking 块中,如果我得到 JSON 响应,我将 JSON 对象分配给定义为属性的数组当前的表视图控制器。

      -(void)locationRequest
      

      { NSURL *url = [NSURL URLWithString:@"myurl"];

      NSURLRequest *request = [NSURLRequest requestWithURL:url];
      //AFNetworking asynchronous url request
      AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                           JSONRequestOperationWithRequest:request
                                           success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
                                           {
      
                                               self.locationsFromJSON = responseObject;
                                               [self.tableView reloadData];
                                           }
                                           failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
                                           {
                                               NSLog(@"Request Failed: %@, %@", error, error.userInfo);
                                           }];
      
      [operation start];
      
      }
      

      我还在 JSON 响应中为每个值声明了一个 Mutable Dictionary 属性和一个 NSString 属性。在下面的 TableVIewCell 方法中,我抓取位于 index.row 的字典对象,并读出键的值并将它们分配给原型单元格标签属性。

       - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      
      static NSString *CellIdentifier = @"locCell";
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    
      if (cell == nil) {
      
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier];
      
      }
      
      
      self.dictObj = [[NSMutableDictionary alloc] init];
      self.dictObj = [_locationsFromJSON objectAtIndex:indexPath.row];
      cell.textLabel.text =  [_dictObj valueForKey:@"city"];  
      cell.detailTextLabel.text = [_dictObj valueForKey:@"phone"];     
      return cell;
      }
      

      这行得通!只是别人指出了明显的“看起来你有一个字典对象数组......”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-05
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        相关资源
        最近更新 更多