Core Data Store included in App Bundle

后端 未结 3 1001
天命终不由人
天命终不由人 2020-12-09 06:02

I can\'t find a clear description of these steps in Apple docs...

  1. I have a xcdatamodeld in my xcode project
  2. At launch time, my app parses a XML (proje
3条回答
  •  没有蜡笔的小新
    2020-12-09 06:37

    You can include the store file (sqlite db most of the time) in your app. Then in your app delegate edit the persistentStoreCoordinator getter merhod :

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
        if (persistentStoreCoordinator_ != nil) {
            return persistentStoreCoordinator_;
        }
    
        NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CoreDataStore.sqlite"];
    
        // Check if the store exists in. 
        if (![[NSFileManager defaultManager] fileExistsAtPath:storePath]) {
            // copy the payload to the store location.
            NSString *bundleStore = [[NSBundle mainBundle] pathForResource:@"YourPayload" ofType:@"sqlite"];
    
            NSError *error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:bundleStore toPath:storePath error:&error];
    
            if (error){
                NSLog(@"Error copying payload: %@", error);
            }
        }
    
        NSError *error = nil;
        NSURL *storeURL = [NSURL fileURLWithPath:storePath];
        persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }    
    
        return persistentStoreCoordinator_;
    }
    

提交回复
热议问题