我想制作一个在Core Data中使用预装数据的应用。这些数据是过去100年来的棒球统计数据。无论如何我使用模拟器创建了一个实体并在以前的版本中保存了数据。
然后我创建了另一个具有相同名称,相同实体的应用程序,并将原始应用程序中的.sqlite文件添加到我的新应用程序mainBundle中。我像在Apple的CoreDataBooksAppDelegate.m示例中那样更新了persistentStoreCoordinator方法,尽管似乎没有预先加载。为什么呢?
#import "AppDelegate.h"
#import "Master.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Test listing all Master data from the store
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Master" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (Master *master in fetchedObjects) {
NSLog(@"first name: %@", master.nameFirst);
NSLog(@"last name: %@", master.nameLast);
NSLog(@"debut: %@", master.debut);
NSLog(@"playerID: %@\n\n", master.playerID);
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "steindorf.Baseball_Stats" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Baseball_Stats" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Baseball_Stats.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:[storeURL path]]){
NSURL *defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"Baseball_Stats" withExtension:@"sqlite"];
if (defaultStoreURL) {
[fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
}
}
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
@end
这是保存在原始版本中的数据,虽然我无法在我的新应用中预先加载
2015-06-06 18:25:14.771 Baseball Stats[12661:637413] first name: Hank
2015-06-06 18:25:14.771 Baseball Stats[12661:637413] last name: Aaron
2015-06-06 18:25:14.772 Baseball Stats[12661:637413] debut: 1954-04-13
2015-06-06 18:25:14.772 Baseball Stats[12661:637413] playerID: aaronha01
2015-06-06 18:25:14.772 Baseball Stats[12661:637413] first name: George
2015-06-06 18:25:14.772 Baseball Stats[12661:637413] last name: Brett
2015-06-06 18:25:14.773 Baseball Stats[12661:637413] debut: 1973-08-02
2015-06-06 18:25:14.773 Baseball Stats[12661:637413] playerID: brettge01
2015-06-06 18:25:14.773 Baseball Stats[12661:637413] first name: Ty
2015-06-06 18:25:14.773 Baseball Stats[12661:637413] last name: Cobb
2015-06-06 18:25:14.773 Baseball Stats[12661:637413] debut: 1905-08-30
2015-06-06 18:25:14.773 Baseball Stats[12661:637413] playerID: cobbty01
2015-06-06 18:25:14.774 Baseball Stats[12661:637413] first name: Tony
2015-06-06 18:25:14.774 Baseball Stats[12661:637413] last name: Gwynn
2015-06-06 18:25:14.774 Baseball Stats[12661:637413] debut: 1982-07-19
2015-06-06 18:25:14.774 Baseball Stats[12661:637413] playerID: gwynnto01
2015-06-06 18:25:14.829 Baseball Stats[12661:637413] first name: Stan
2015-06-06 18:25:14.829 Baseball Stats[12661:637413] last name: Musial
2015-06-06 18:25:14.829 Baseball Stats[12661:637413] debut: 1941-09-17
2015-06-06 18:25:14.830 Baseball Stats[12661:637413] playerID: musiast01
我认为这会起作用 - 这种方法是否合适
而不是预加载数据,在app lauches时创建NSFetchRequest,如果managedObjects数组== 0,则开始保存所有数据。这样,只有在应用程序首次启动时才会创建并保存所有实体对象。当然,大部分数据将被创建并保存dispatch_async,因此用户不会等待第一次加载所有内容
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSError *error;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"miniMaster" ofType:@"json"];
NSArray* MASTER = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&error];
// Test listing all Baseball_Stats from the store
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Master" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"%d", (int)[fetchedObjects count]);
//if fetchRequest doesn't find any objects for selected entity, load and save data
if([fetchedObjects count] == 0){
for (id m in MASTER) {
Master *master = [NSEntityDescription insertNewObjectForEntityForName:@"Master"
inManagedObjectContext:self.managedObjectContext];
master.nameFirst = [m objectForKey:@"nameFirst"];
master.nameLast = [m objectForKey:@"nameLast"];
master.debut = [m objectForKey:@"debut"];
master.playerID = [m objectForKey:@"playerID"];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
}
for (Master *master in fetchedObjects) {
NSLog(@"first name: %@", master.nameFirst);
NSLog(@"last name: %@", master.nameLast);
NSLog(@"debut: %@", master.debut);
NSLog(@"playerID: %@\n\n", master.playerID);
}
return YES;
}
答案 0 :(得分:0)
看起来问题是您正在复制.sqlite
文件而不是日记文件(wal
和shm
文件)。使用默认的SQLite日志模式,大多数数据将最终存储在日志文件中。确保你得到所有这些。