【问题标题】:Preloading default data into Core Data - iOS将默认数据预加载到 Core Data - iOS
【发布时间】:2015-08-21 17:56:42
【问题描述】:

我想制作一个使用 Core Data 中预加载数据的应用。数据是过去 100 年的棒球统计数据。无论如何,我使用模拟器创建了一个实体并在以前的版本中保存了数据。

然后我创建了另一个具有相同名称、相同实体的应用程序,并将原始应用程序中的 .sqlite 文件添加到我的新应用程序 mainBundle 中。我更新了 persistentStoreCoordinator 方法,就像在 Apple 的 CoreDataBooksAppDelegate.m 示例中所做的那样,尽管似乎没有预加载任何内容。为什么?

#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

我认为这行得通 - 这种方法是否合适

不是预加载数据,而是在应用启动时发出 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;
}

【问题讨论】:

  • 为什么不使用同一个应用程序来生成初始数据?我会假设有一些元数据会导致不同包的商店不兼容。
  • 你在defaultStoreURL有什么收获吗?
  • 我可以接受这种方法,在应用启动时发出 NSFetchRequest 并且如果 managedObjects 数组 == 0,则保存所有数据。这样,所有实体对象都将在应用程序首次启动时创建并保存,而不是预加载数据。当然,大部分数据将被创建并保存 dispatch_async 所以用户不会等待第一次加载所有内容
  • @ntsh 我应该在 defaultStoreURL 中检查什么。 Baseball_Stats.sqlite 文件(/Users/jsteindorf/Library/Developer/CoreSimulator/Devices/527223BD-EB6A-4B69-8289-67F27D9DC0EE/data/Containers/Data/Application/BB5B615F-8293-4E9C-A718-A5D65D4EE4B6/Documents/Baseball_Stats .sqlite) 在那里,但它是机器代码,所以我无法实际看到它是什么,尽管似乎没有加载任何内容,所以我认为它没有保存任何对象
  • 您可以在终端中使用sqlite3 Baseball_Stats.sqlite 命令来使用SQL 命令浏览数据。但是,我在问您的 defaultStoreURL 是否为 Null,如果您在代码中放置断点。如果它为空,可能您在将数据库复制到项目时没有选中Copy Items if Needed 复选框。此外,您的第二种方法似乎还可以。

标签: ios objective-c core-data


【解决方案1】:

问题似乎在于您正在复制 .sqlite 文件而不是日志文件(walshm 文件)。使用默认的 SQLite 日志模式,大部分数据将最终保存在日志文件中。确保你得到所有这些。

【讨论】:

  • 我添加了 2 个文件,但仍然没有运气,它们在我的 didFinishLaunchingWithOptions 中没有按预期进行 NSLog。我更新了图像以显示此
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
相关资源
最近更新 更多