gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:30:52 26 4
gpt4 key购买 nike

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

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

有更好的方法吗?

此外,我尝试对实体执行一个简单的 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;
}

最佳答案

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

如果发生 错误

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? 。)

关于ios - 在运行时检查/加载核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19798723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com