xcode 核心数据数据库为空测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4956905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:12:41  来源:igfitidea点击:

core data database is empty test

objective-cdatabasexcodecore-data

提问by Csabi

How can I test if the core data database is empty? I tried:

如何测试核心数据数据库是否为空?我试过:

NSIndexPath *path1 = [NSIndexPath indexPathForRow:0 inSection:0];
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:path1];
if([[managedObject valueForKey:@"date"] description]!=nil){SOMEFUNCTION}else{SOMEFUNCTION}

Thanks

谢谢

回答by Matthias Bauch

you have to create a fetchrequest for each entity you use in core data. if the fetchrequest returns without results you don't have objects of this entity stored in your core data.

您必须为您在核心数据中使用的每个实体创建一个 fetchrequest。如果 fetchrequest 返回而没有结果,则您的核心数据中没有存储此实体的对象。

- (BOOL)coreDataHasEntriesForEntityName:(NSString *)entityName {
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
    [request setEntity:entity];
    [request setFetchLimit:1];
    NSError *error = nil;
    NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (!results) {
        LogError(@"Fetch error: %@", error);
        abort();
    }
    if ([results count] == 0) {
        return NO;
    }
    return YES;
}

回答by Csabi

not perfect I admit but it works

我承认并不完美,但它有效

my code:

我的代码:

id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
    int fufu = [sectionInfo numberOfObjects];
    if(fufu!=0){DATABASE IS NOT EMPTY}else{DATABASE IS EMPTY}

if someone know something more efective pls post it

如果有人知道更有效的东西,请发布它

回答by Elias

I have these two methods implemented in my appDelegate:

我在我的 appDelegate 中实现了这两种方法:

- (NSString *)applicationDocumentsDirectory 

{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

    return basePath;

}

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator 

    {

        if (persistentStoreCoordinator != nil) 

            return persistentStoreCoordinator;

        NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"YourApp.sqlite"]];

        NSLog(@"storeURL: %@", storeUrl);

        NSError *error;

        persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

        NSDictionary * options = [NSDictionary dictionaryWithObjectsAndKeys:  

                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,  

                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];  

        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 

            Typical reasons for an error here include: 
            * The persistent store is not accessible 
            * The schema for the persistent store is incompatible with current managed object model 
            Check the error message to determine what the actual problem was. 
            */


        }// if    

        return persistentStoreCoordinator;
    }

The storeUrl prints the path to the sqlite database.

storeUrl 打印到 sqlite 数据库的路径。

If you open this path with a sqlite manager, you're able to see the content of your sql database. I use this SQLite Manager to analyze sqlite databases: SQLite Manager

如果你用sqlite管理器打开这个路径,你就可以看到你的sql数据库的内容。我使用这个 SQLite Manager 来分析 sqlite 数据库:SQLite Manager

(You can only use this method on the simulator)

(此方法只能在模拟器上使用)