Pregunta

I have a plist file which is an array of dictionaries. Where each dictionary contains a set of strings. Each dictionary represents a celebrity.

What I would like to do is populate Core Data with the contents of this plist on the applications first launch, after which I would like to somehow check core data for the existence of my data, and if there is data, load it from there, otherwise load the initial data from the plist file again.

I know its possible to populate core data from a plist, but is what I'm suggesting a viable solution? Or is there a better approach?

Jack

¿Fue útil?

Solución

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];
}

Otros consejos

This is doing the same thing but with a slightly more complex pList that contains an array of dictionaries representing data on a "topic" to be stored. It still has some of the debug logging in place. Hope it is useful 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);
    };
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top