Is Core Data useful for readonly data too?

前端 未结 5 678
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 15:36

I\'m creating an iPhone App and am wondering whether Core Data is better for readonly data than a SQLite database. It feels like the SQLite DB is the better choice, is that

5条回答
  •  死守一世寂寞
    2020-12-23 16:10

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

提交回复
热议问题