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

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

我想把这个.txt文件保存到core data中

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 后,代码现在可以完美运行

关于ios - 将带有部分的大文本文件保存到核心数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27882306/

相关文章:

iOS 从 .plist 文件加载数据

ios - ABAddressBookSave 导致 EXC_BAD_ACCESS ARC 已启用

ios - 隐藏 View 时如何使用自动布局移动其他 View ?

ios - 如何使用 iOS 轻松调整/优化图像大小?

iphone - 将 iPad 应用程序中的文本数据保存为可以从 "notes app"打开的注释?

ios - 为什么编辑器里预览给错iphone型号

iphone - UIDocumentInteractionController : open file whith native application

当 native 闹钟响起时发送推送通知的 iOS 应用程序

ios - Core-Data NSFetchedResultsController 对多关系

ios - Swift 中 @discardableResult 声明的 ObjC 版本是什么