Load data into core-data schema

前端 未结 3 1051
渐次进展
渐次进展 2021-01-31 12:53

I am implementing a navigation-based application. The user will drill down to the node of interest. I am using Core Data, mostly because I want to try it out. How do I load the

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 13:31

    Here's a simple way to preload the Core Data store using plists.

    Make a property list containing an array of dictionaries. Make the keys of each dictionary correspond to the keys of your managed object.

    Then, call this method the first time the app launches:

    - (void)loadDataFromPropertyList {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"plist"];
        NSArray *items = [NSArray arrayWithContentsOfFile:path];
    
        NSManagedObjectContext *ctx = self.managedObjectContext;
    
        for (NSDictionary *dict in items) {
            NSManagedObject *m = [NSEntityDescription insertNewObjectForEntityForName:@"TheNameOfYourEntity" inManagedObjectContext:ctx];
            [m setValuesForKeysWithDictionary:dict];
        }
    
        NSError *err = nil;
        [ctx save:&err];
    
        if (err != nil) {
            NSLog(@"error saving managed object context: %@", err);
        }
    }
    

    Call loadDataFromPropertyList the first time the app launches by including the following code in the implementation of application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
    if (![defaults objectForKey:@"firstRun"])
    {
        [defaults setObject:[NSDate date] forKey:@"firstRun"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self loadDataFromPropertyList];
    }
    

提交回复
热议问题