将带有部分的大文本文件保存到核心数据属性

Saving large text file with sections to Core Data attributes

我想将此 .txt 文件保存到核心数据

http://openweathermap.org/help/city_list.txt

但是如您所见,它有 5 个不同的部分 1)id(城市ID) 2)纳米(名称) 3)lat(纬度) 4)lon(经度) 5)国家代码

我想下载文件并将每个部分保存到核心数据属性中。 我环顾四周,找不到有关如何执行此操作的任何信息。我是核心数据和数据库的初学者,如果这是一个新手问题,我很抱歉。

谢谢,如果我可以提供任何其他信息,请告诉我

您在这里要做的第一件事就是下载数据。您可以使用 NSURLConnection 来做到这一点。然后你想逐行阅读它,以获得不同的城市。当您逐行阅读它时,您可以通过使用制表符 (\t) 分隔它们来获取每个单独的字段。当你有每个单独的字段时,记得将它们放入数据库中。

示例代码:

- (void)downloadAndParseCityList {
    NSURL *listURL = [NSURL URLWithString:@"http://openweathermap.org/help/city_list.txt"];
    NSURLRequest *request = [NSURLRequest requestWithURL:listURL]; //Forge the request to be used by NSURLConnection.
    NSData *cityData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //You probably use an asynchrounous request instead, but I'm too lazy to do that here.

    NSString *cityString = [[NSString alloc] initWithData:cityData encoding:NSASCIIStringEncoding]; //We're going to work with the data as an NSString.

    NSArray *cities = [cityString componentsSeparatedByString:@"\n"]; //By getting the components seperated by line-break, it is easier to work with each individual city more like an object.

    for(NSUInteger i = 1; i <= [cities count]-1; i++) { //We start at i=1 because we don't want to parse the first line in the file ("id    nm  lat lon countryCode"), as these are just the field names.
        NSString *cityString = cities[i];
        NSArray *cityFields = [cityString componentsSeparatedByString:@"\t"]; //All the fields are seperated by a tab ('\t'), that makes it easy to read all the fields.

        for(NSString *field in cityFields) {
        //Here you probably want to do something with the fields. Save them to a Core Data database or something.
        }
    }
}

您必须自己弄清楚关于 Core Data 的部分,因为我还没有充分使用它来适应发布任何关于它的内容作为答案。

(代码尚未经过测试,因此可能无法开箱即用。)

编辑: 抱歉,代码根本不起作用,似乎数据对于 NSString 来说太大了,但答案的第一部分仍然适用。首先通过换行符 (\n) 解析每个单独的城市,然后通过制表符 (\t) 解析每个字段。

编辑 2:

将编码更改为 NSASCIIStringEncoding

后,代码现在可以完美运行