Pre-populated baseline data using only for the first application launch

I have a plist file, which is a collection of dictionaries. Where each dictionary contains a set of lines. Each dictionary represents a celebrity.

What I would like to do is fill the Core Data with the contents of this plist on the first launch of the application, after which I would like to somehow check the main data for the presence of my data, and if there is data, download it from there, otherwise load it again source data from the plist file.

I know that it can be populated with kernel data from plist, but is this what I suggest for a viable solution? Or is there a better approach?

Jack

+4
source share
2 answers

My sample code

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if (![defaults objectForKey:@"dataImported"]) { NSString *path = [[NSBundle mainBundle] pathForResource:@"dict" ofType:@"plist"]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; for (NSString *key in [dict allKeys]) { NSDictionary *node = [dict objectForKey:key]; MyClass *newObj = ..... } [defaults setObject:@"OK" forKey:@"dataImported"]; [defaults synchronize]; } 
+8
source

This does the same, but with a slightly more complex pList, which contains an array of dictionaries representing the data in the "topic" that needs to be saved. It still has some of the debugging protocols. Hope this is helpful to someone.

 NSManagedObjectContext *context = self.managedObjectContext; NSError *error; NSFetchRequest *topicRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *topicEntityDescription = [NSEntityDescription entityForName:@"Topic" inManagedObjectContext:context]; [topicRequest setEntity:topicEntityDescription]; NSManagedObject *newTopic = nil; NSArray *topics = [context executeFetchRequest:topicRequest error:&error]; if (error) NSLog(@"Error encountered in executing topic fetch request: %@", error); if ([topics count] == 0) // No topics in database so we proceed to populate the database { NSString *topicsPath = [[NSBundle mainBundle] pathForResource:@"topicsData" ofType:@"plist"]; NSArray *topicsDataArray = [[NSArray alloc] initWithContentsOfFile:topicsPath]; int numberOfTopics = [topicsDataArray count]; for (int i = 0; i<numberOfTopics; i++) { NSDictionary *topicDataDictionary = [topicsDataArray objectAtIndex:i]; newTopic = [NSEntityDescription insertNewObjectForEntityForName:@"Topic" inManagedObjectContext:context]; [newTopic setValuesForKeysWithDictionary:topicDataDictionary]; [context save:&error]; if (error) NSLog(@"Error encountered in saving topic entity, %d, %@, Hint: check that the structure of the pList matches Core Data: %@",i, newTopic, error); }; } 
0
source

Source: https://habr.com/ru/post/1403343/


All Articles