вот пример метода, который я использую в своем приложении для iOS, чтобы загрузить текстовый файл с разделителями (с использованием символа «|» в качестве разделителя полей), который содержит данные о нескольких видах растений и животных. файл хранится в каталоге документов приложения, поэтому пользователь может добавить / изменить его через общий доступ к документам через iTunes. файл называется «X.specieslist», где X совпадает с именем базы данных sqlite, управляемой Core Data. Код проверяет, что данный вид еще не присутствует в базе данных (на основе ключа 'code'), и импортирует только те виды, которых нет.
- (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];
}
}