gpt4 book ai didi

ios - 使用 JSON 数组填充 UITableView

转载 作者:可可西里 更新时间:2023-11-01 03:36:42 24 4
gpt4 key购买 nike

我在 Storyboard 工作,但我想现在是时候面对代码了......

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

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

我最终会需要所有数据,但现在我只想将城市字段输出为 UITableView。我该怎么做呢?

最佳答案

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

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

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

#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 文件中添加此代码

#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 字段表还是city and name 表等。通过这样做,您还可以避免项目中到处都是 json 解码代码。当您的“ key ”名称更改时会发生什么?无需遍历代码更正所有键,您只需转到 PlaceDataObject 类并更改适当的 key,您的应用程序将继续工作。

Apple 很好地解释了这一点:

“模型对象代表特殊知识和专长。它们保存应用程序的数据并定义操作该数据的逻辑。设计良好的 MVC 应用程序将其所有重要数据封装在模型对象中......它们代表与特定问题领域相关的知识和专业知识,它们往往是可重用的。”

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

现在开始填充您创建的自定义数据对象的数组。现在遵循 MVC 方法,最好将处理数据的所有方法都放在不同的类(模型类)中。这就是 Apple 建议将这些类型的方法放在一个单独的模型类中,所有处理都在该类中进行。

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

在您的 View Controller 的 m 文件中创建一个方法来处理您的 JSON 数组。

//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
}
}

你会像这样调用上面的方法:

//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 中填充数据,您可以这样做:

- (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);
}

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

关于ios - 使用 JSON 数组填充 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com