ObjectiveC - 平面文件到 CoreData

发布于 2024-11-09 10:11:12 字数 256 浏览 0 评论 0原文

我有一个包含 100 万行的大文件。文件设置如下:

A1 B1 C1 D1 E1
A2 B2 C2 D2 E2
A3 B3 C3 D3 E3

我想将此数据读入由 CoreData 管理的 SQLite 数据库中。

做到这一点最有效和最有效的方法是什么?

这可以通过使用 CoreData & 来实现。 Objective-C 或创建一个 SQLite 数据库,然后将其导入到使用 CoreData 的项目中。

I have a large file with 1 million rows. The file is setup as follows:

A1 B1 C1 D1 E1
A2 B2 C2 D2 E2
A3 B3 C3 D3 E3

I want to read this data into a SQLite database which is managed by CoreData.

What is the most efficient and effective way of doing this?

This could be achieved by either using CoreData & Objective-C or creating an SQLite database that is then imported into the project which uses CoreData.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦在深巷 2024-11-16 10:11:12

如果这不是您需要即时执行的操作,那么我可能会编写某种脚本:(1)创建数据库/架构,然后(2)从文件中读取并插入到适当的表中。然后我将数据库导入到项目中。

If this isn't something you need to do on the fly, then I'd probably write a script of some kind that: (1) creates the database/schema, then (2) reads from the file and inserts into the appropriate tables. I'd then import the database into the project.

兮颜 2024-11-16 10:11:12

下面是我在 iOS 应用程序中使用的方法示例,用于加载分隔文本文件(使用竖线“|”作为字段分隔符),其中包含有关多种植物和动物物种的数据。该文件存储在应用程序的文档目录中,以便用户可以通过 iTunes 通过文档共享来添加/更改它。该文件名为“X.specieslist”,其中 X 与 Core Data 管理的 sqlite 数据库同名。该代码检查数据库中是否已存在给定物种(基于“代码”键),并且仅导入那些不存在的物种。

- (void)loadSpecies {

    //get path to species file stored in Documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSPersistentStoreCoordinator *psc = [managedObjectContext persistentStoreCoordinator];
    NSArray *psa = [psc persistentStores];
    NSURL *psurl = [[psa objectAtIndex: 0] URL];
    NSString *filestr = [[psurl lastPathComponent] stringByReplacingOccurrencesOfString: @"sqlite" withString: @"specieslist"] ;
    NSString *filePath = [basePath stringByAppendingPathComponent: filestr];

    //create array with each element containing a single line from the input file
    NSArray *speciesRecords = [[NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil] componentsSeparatedByString: @"\n"];

    if (speciesRecords) {
        int speciesAdded = 0;
        int speciesSkipped = 0;
        NSEntityDescription *entity = [NSEntityDescription entityForName: @"Species" inManagedObjectContext: managedObjectContext];
        NSManagedObject *newSpecies;
        NSDictionary *speciesDictionary;
        NSArray *fieldKeys = [[NSArray alloc] initWithObjects: @"code", @"scientificName", @"commonName", @"family", @"lifeform", @"growthForm", @"lifecycle", @"nativity", @"notes", nil];
        NSArray *fieldValues;
        NSArray *existingRecords = [fetchedResultsController fetchedObjects];
        NSPredicate *speciesCodePred;
        NSArray *speciesMatch;

        for (NSString *species in speciesRecords) {
            fieldValues = [species componentsSeparatedByString: @"|"];

            //check if species code already exists
            speciesCodePred = [NSPredicate predicateWithFormat: @"code MATCHES %@", [fieldValues objectAtIndex: 0] ];
            speciesMatch = [existingRecords filteredArrayUsingPredicate: speciesCodePred];

            //only add species not already present
            if ([speciesMatch count] == 0) {
                newSpecies = [[NSManagedObject alloc] initWithEntity: entity insertIntoManagedObjectContext: managedObjectContext];
                speciesDictionary = [NSDictionary dictionaryWithObjects: fieldValues forKeys: fieldKeys];
                [newSpecies setValuesForKeysWithDictionary: speciesDictionary];
                [newSpecies release];
                speciesAdded++;
            }
            else
                speciesSkipped++;
        }
        [fieldKeys release];
        NSString *speciesSkippedString = (speciesSkipped > 0) ? [NSString stringWithFormat: @" and %d species were skipped because they were already present.", speciesSkipped] : @".";

        UIAlertView *av = [[UIAlertView alloc] initWithTitle: @"Species List Import" message: [NSString stringWithFormat: @"%d species were added to the database%@", speciesAdded, speciesSkippedString] delegate: nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
        [av show];
        [av release];
    }

    else {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle: @"Species List Import" message: @"A species list file was not present, no species were imported." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [av show];
        [av release];
    }
}

here's an example of a method i use in my iOS app to load a delimited text file (using a pipe "|" as the field delimiter) that contains data about several plant and animal species. the file is stored in the app's Documents directory so the user can add/change it via document sharing through iTunes. the file is named 'X.specieslist', where X is the same name as the sqlite database being managed by Core Data. The code checks that a given species isn't already present in the database (based on the 'code' key), and only imports those species not present.

- (void)loadSpecies {

    //get path to species file stored in Documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSPersistentStoreCoordinator *psc = [managedObjectContext persistentStoreCoordinator];
    NSArray *psa = [psc persistentStores];
    NSURL *psurl = [[psa objectAtIndex: 0] URL];
    NSString *filestr = [[psurl lastPathComponent] stringByReplacingOccurrencesOfString: @"sqlite" withString: @"specieslist"] ;
    NSString *filePath = [basePath stringByAppendingPathComponent: filestr];

    //create array with each element containing a single line from the input file
    NSArray *speciesRecords = [[NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil] componentsSeparatedByString: @"\n"];

    if (speciesRecords) {
        int speciesAdded = 0;
        int speciesSkipped = 0;
        NSEntityDescription *entity = [NSEntityDescription entityForName: @"Species" inManagedObjectContext: managedObjectContext];
        NSManagedObject *newSpecies;
        NSDictionary *speciesDictionary;
        NSArray *fieldKeys = [[NSArray alloc] initWithObjects: @"code", @"scientificName", @"commonName", @"family", @"lifeform", @"growthForm", @"lifecycle", @"nativity", @"notes", nil];
        NSArray *fieldValues;
        NSArray *existingRecords = [fetchedResultsController fetchedObjects];
        NSPredicate *speciesCodePred;
        NSArray *speciesMatch;

        for (NSString *species in speciesRecords) {
            fieldValues = [species componentsSeparatedByString: @"|"];

            //check if species code already exists
            speciesCodePred = [NSPredicate predicateWithFormat: @"code MATCHES %@", [fieldValues objectAtIndex: 0] ];
            speciesMatch = [existingRecords filteredArrayUsingPredicate: speciesCodePred];

            //only add species not already present
            if ([speciesMatch count] == 0) {
                newSpecies = [[NSManagedObject alloc] initWithEntity: entity insertIntoManagedObjectContext: managedObjectContext];
                speciesDictionary = [NSDictionary dictionaryWithObjects: fieldValues forKeys: fieldKeys];
                [newSpecies setValuesForKeysWithDictionary: speciesDictionary];
                [newSpecies release];
                speciesAdded++;
            }
            else
                speciesSkipped++;
        }
        [fieldKeys release];
        NSString *speciesSkippedString = (speciesSkipped > 0) ? [NSString stringWithFormat: @" and %d species were skipped because they were already present.", speciesSkipped] : @".";

        UIAlertView *av = [[UIAlertView alloc] initWithTitle: @"Species List Import" message: [NSString stringWithFormat: @"%d species were added to the database%@", speciesAdded, speciesSkippedString] delegate: nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
        [av show];
        [av release];
    }

    else {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle: @"Species List Import" message: @"A species list file was not present, no species were imported." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [av show];
        [av release];
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文