使用JSON数组填充UITableView [英] Populate UITableView with JSON array

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

问题描述

我正在使用Storyboard,但我认为现在是时候面对代码...

I'm working in Storyboard but I presume now it's time to face the code...

我的服务器上有一个PHP文件输出的内容我的MySQL数据库表格为JSON格式的数组:

I have a PHP file on my server which outputs the contents of my MySQL database table as an array in JSON format:

{
"id":"2",
"name":"The King's Arms",
"city":"London",
"day":"Tuesday",
}

我最终需要所有数据,但是现在我只想将城市字段输出为UITableView。我将如何做到这一点?

I'll need all the data eventually, but for now I just want to output the city fields as a UITableView. How would I go about doing this?

推荐答案

我相信是在2012/2013学年,Apple播放了一段精彩视频代码实践,突出显示的一个子主题是处理JSON对象和为它们创建数据对象的一种很好的智能方法。对不起,我忘记了实际视频的名称,如果有人记得,请为我编辑答案。

I believe it was in the year 2012/2013 where Apple covered a fantastic video on code practices, one sub topic highlighted was a good smart way of handling JSON objects and creating data objects for them. I'm sorry I forgot the name of the actual video, if someone remembers it please do edit the answer for me.

苹果所涵盖的数据对象是什么存储每个json对象。然后,我们将创建一个数组来存储这些对象,并在填充tableView时适当地访问所需的字段。所以在你的情况下,你会做这样的事情。

What apple covered was to have a data object that stores each json object. We will then create an array to store these objects and access the required fields appropriately when populating our tableView. So in your case you would do something like this.

在你的项目导航器中添加一个NSObject类型的文件并添加以下代码:

in your project navigator add a file of NSObject type and add the following code:

#import <Foundation/Foundation.h>
@interface PlaceDataObject : NSObject

-(id)initWithJSONData:(NSDictionary*)data;

@property (assign) NSInteger placeId;
@property (strong) NSString *placeName;
@property (strong) NSString *placeCity;
@property (strong) NSString *placeDay;

@end

和你的 .m 您要添加此代码的文件

and in your .m file you would add this code

#import "PlaceDataObject.h"
@implementation PlaceDataObject
@synthesize placeId;
@synthesize placeName;
@synthesize placeCity;
@synthesize placeDay;

-(id)initWithJSONData:(NSDictionary*)data{
    self = [super init];
    if(self){
        //NSLog(@"initWithJSONData method called");
        self.placeId = [[data objectForKey:@"id"] integerValue];
        self.placeName =  [data objectForKey:@"name"];
        self.placeCity = [data objectForKey:@"city"];
        self.placeDay = [data objectForKey:@"day"];
    }
    return self;
}
@end

你现在拥有的是一个数据对象类您可以在任何需要的代码中随处使用,并获取您所显示的任何表的相应详细信息,无论是 city 字段表还是城市并且名称 table等。通过这样做,您还可以避免在项目中的任何地方使用json解码代码。当钥匙的名称发生变化时会发生什么?您只需转到 PlaceDataObject 类并更改适当的,而不是仔细检查所有密钥的代码。你的申请将继续有效。

What you have now is a data object class which you can use everywhere in your code where ever required and grab the appropriate details for whichever table youre showing, whether it be a city fields table or a city and name table etc. By doing this you will also avoid having json decoding code everywhere in your project. What happens when the name of your 'keys' changes? rather than scouring through your code correcting all your keys, you simply go to the PlaceDataObject class and change the appriopriate key and your application will continue working.

Apple解释得很好:

Apple explains this well:

模型对象代表特殊知识他们持有应用程序的数据并定义操纵该数据的逻辑。精心设计的MVC应用程序将其所有重要数据封装在模型对象中....它们代表与特定问题域相关的知识和专业知识,它们倾向于可以重复使用。

使用自定义对象为服务器中的每个json条目填充数组

现在填充您已经制作的这个自定义数据对象的数组。现在遵循MVC方法,您可能最好拥有处理不同类(Model类)中的数据的所有方法。这就是Apple建议将这些方法放在一个单独的模型类中,其中所有处理都会发生。

Now onto populating an array of this custom data object you've made. Now following the MVC approach, it's probably best that you have all your methods that process data in a different class, your Model class. That's what Apple recommends to put these kind of methods in a seperate model class where all the processing happens.

但是现在我们只是将下面的代码添加到View Controller仅用于演示目的。

But for now we are just going to add the below code to the View Controller just for demonstration purposes.

在视图控制器的m文件中创建一个处理JSON数组的方法。

Create a method in your view controller's m file that will process your JSON array.

//make sure you have a global NSMutableArray *placesArray in your view controllers.h file.
-(void)setupPlacesFromJSONArray:(NSData*)dataFromServerArray{
     NSError *error;
     NSMutableArray *placesArray = [[NSMutableArray alloc] init];
     NSArray *arrayFromServer = [NSJSONSerialization JSONObjectWithData:dataFromServerArray options:0 error:error];

     if(error){
         NSLog(@"error parsing the json data from server with error description - %@", [error localizedDescription]);
     } 
     else {
         placesArray = [[NSMutableArray alloc] init];
         for(NSDictionary *eachPlace in arrayFromServer)
         {
             PlaceDataObject *place = [PlaceDataObject alloc] initWithJSONData:eachPlace];
             [placesArray addObject:place];
         }

         //Now you have your placesArray filled up with all your data objects
     }
 }

您可以这样调用上述方法:

And you would call the above method like so:

//This is not what your retrievedConnection method name looks like ;)
// but you call the setupPlacesFromJSONArray method inside your connection success method
-(void)connectionWasASuccess:(NSData *)data{
    [self setupPlacesFromJSONArray:data];
}

使用自定义数据对象填充tableView

至于在TableView中填充数据,你可以这样做:

As for populating your data in your TableView you do so like this:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     //We check against table to make sure we are displaying the right number of cells
     // for the appropriate table. This is so that things will work even if one day you 
     //decide that you want to have two tables instead of one.
     if(tableView == myCitysTable){
          return([placesArray count]);
     }
     return 0;
}


 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
     if(cell)
     {
          //set your configuration of your cell
     }
     //The beauty of this is that you have all your data in one object and grab WHATEVER you like
     //This way in the future you can add another field without doing much.

     if([placesArray count] == 0){
         cell.textLabel.text = @"no places to show";
     }
     else{
         PlacesDataObject *currentPlace = [placesArray objectAtIndex:indexPath.row];
         cell.textLabel.text = [currentPlace placeCity];
         // in the future you can grab whatever data you need like this
         //[currentPlace placeName], or [currentPlace placeDay];
     }    
     return(cell);
}

简短免责声明:上述代码尚未经过测试,但请如果一切正常或者我遗漏了任何字符,请告诉我。

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

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