core data database is empty test

前端 未结 3 1036
失恋的感觉
失恋的感觉 2021-01-13 09:28

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

NSIndexPath *path1 = [NSIndexPath indexPathForRow:0 inSection:0];
NSManagedObject *managedObject          


        
3条回答
  •  北海茫月
    2021-01-13 09:58

    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.

    - (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;
    }
    

提交回复
热议问题