gpt4 book ai didi

ios - 将 .csv 读入 NSObjects,然后按不同的标准对它们进行排序

转载 作者:技术小花猫 更新时间:2023-10-29 11:15:11 26 4
gpt4 key购买 nike

这是一个开放性问题,而不是与错误相关的问题,所以如果您不想回答这类问题,请不要发火。

我在 .csv 文件中有一个巨大的(!)船舶列表,由 , 分隔

矩阵是这样组织的: enter image description here
用不同的数据重复大约 500 次。

现在,我希望将其读入对象,这些对象可进一步用于填充 UITableView目前,我将数据硬编码到目标文件中,就像这样

arrayWithObjectsForTableView = [[NSMutableArray alloc] init];
if ([boatsFromOwner isEqualToString:@"Owner1"]) {
cargoShips* ship = [[cargoShips alloc]init];
ship.name = @"name1";
ship.size = 1000;
ship.owner = @"Owner1";

[self.boatsForOwner addObject:ship];

ship = [[cargoShips alloc]init];
ship.name = @"Name 2";
ship.size = 2000;
ship.owner = @"Owner2";

依此类推 if-else 的。这是一个糟糕的方法,因为1)它很无聊,需要很长时间2) 如果我要更新信息,则需要更多时间。因此,我认为以编程方式从矩阵中读取而不是自己读取会更聪明。是的,船长显然是来参观我的大脑的。

那么,问题来了!如何读取如下所示的 .csv 文件: enter image description here以对象的形式将所有者的船只添加到 NSMutableArray 中。 (所以它们可以用来为我的 UITableView 提供船只。

我还希望可以选择按不同的东西排序,例如构建国家/地区、运营商等。如何编写代码,将相关船只从 .csv 读取到对象中?我不太了解编程,因此非常感谢深入的答案。

最佳答案

处理的深度将决定此任务需要哪种数据结构。这是我会使用的方法:

1:.csv文件读入一个巨大的NSString对象:

NSString *file = [[NSString alloc] initWithContentsOfFile:yourCSVHere];

2:获取单独的行:

NSArray *allLines = [file componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

3:对于每一行,获取单独的组件:

for (NSString* line in allLines) {
NSArray *elements = [line componentsSeparatedByString:@","];
// Elements now contains all the data from 1 csv line
// Use data from line (see step 4)
}

4:这取决于您。我的第一个想法是创建一个类来存储所有数据。例如:

@interface Record : NSObject
//...
@property (nonatomic, copy) NSString *name
@property (nonatomic, copy) NSString *owner
// ... etc
@end

4a: 然后,回到第 3 步,为每一行创建一个 Record 对象,然后将所有 Record 对象放入一个单独的 NSArray (范围更大的东西!)。

5:使用包含所有 Record 对象的 NSArray 作为 UITableView 的数据源。

第 4 步和第 5 步的实现由您决定。对于中等大小的 .csv 文件,我可能会这样做。

编辑:这是生成记录的方法。

//
NSMutableArray *someArrayWithLargerScope = [[NSMutableArray alloc] init];
//

NSString *file = [[NSString alloc] initWithContentsOfFile:yourCSVHere];
NSArray *allLines = [file componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet];

for (NSString* line in allLines) {
NSArray *elements = [line componentsSeparatedByString@","];
Record *rec = [[Record alloc] init];
rec.name = [elements objectAtIndex:0];
rec.owner = [elements objectAtIndex:1];
// And so on for each value in the line.
// Note your indexes (0, 1, ...) will be determined by the
// order of the values in the .csv file.
// ...
// You'll need one `Record` property for each value.

// Store the result somewhere
[someArrayWithLargerScope addObject:rec];
}

关于ios - 将 .csv 读入 NSObjects,然后按不同的标准对它们进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14447425/

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