【问题标题】:Saving large text file with sections to Core Data attributes将带有部分的大型文本文件保存到 Core Data 属性
【发布时间】:2015-03-09 01:22:48
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: ios objective-c cocoa-touch core-data


    【解决方案1】:

    您在这里要做的第一件事是下载数据。您可以使用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.
            }
        }
    }
    

    您必须自己弄清楚有关核心数据的部分,因为我没有充分利用它来发布任何关于它的内容作为答案。

    (代码尚未经过测试,因此可能无法直接使用。)

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

    编辑2:

    将编码更改为NSASCIIStringEncoding 后,代码现在可以完美运行

    【讨论】:

    • 你的第一个答案是错误的,但不是你想的那样。一个 NSString 可以容纳超过 300,000 个字节。问题是编码实际上是NSASCIIStringEncoding。谢谢你的回答
    • 哦,我想我只是太习惯 UTF8Encoding 了。希望你能从答案中得到一些东西。
    • 绝对是一个值得一试的有用答案。
    • 另外,您应该使用NSUInteger,它是一个 64 位 int 来处理这样的大量数据。只是一个提示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2013-09-20
    • 2023-03-29
    • 2020-11-12
    • 2021-08-17
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多