在运行时检查/加载核心数据

时间:2013-11-05 20:52:12

标签: ios objective-c core-data

我有一个名为Holidays的实体应用。我需要为我的应用程序预先填充几年的假期。

我想我可以通过在AppDelegate didFinishLaunchingWithOptions方法中放置代码来检查Holidays实体并在运行时加载它...我可以检查并查看它是否已经有记录,如果没有,添加它们英寸

有更好的方法吗?

另外,我尝试在实体上执行一个简单的fetchrequest来计算记录(作为查看它是否已经加载的一种方式),但不断收到我的数组为空的错误。如何检查实体是否为空而没有错误输出?

这当然死了,但这就是我的尝试:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // set up the default data

    //holiday dates
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Holidays" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"The entity is empty");
    }
    else {

        NSLog(@"The entity is loaded");
    }

    return YES;
}

1 个答案:

答案 0 :(得分:1)

这是“两个问题合二为一”,所以我将回答第二个问题: - )

如果发生错误,则

executeFetchRequest会返回nil。所以你的检查应该 看起来像:

NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // report error
} else if ([fetchedObjects count] == 0) {
    NSLog(@"The entity is empty");
}
else {
    NSLog(@"The entity is loaded");
}

(要预先填充数据库,请查看Any way to pre populate core data?。)

相关问题