основная база данных - пустой тест - PullRequest
5 голосов
/ 10 февраля 2011

Как я могу проверить, пуста ли основная база данных? Я попробовал:

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

Спасибо

Ответы [ 3 ]

18 голосов
/ 10 февраля 2011

Вы должны создать запрос на выборку для каждой сущности, которую вы используете в основных данных. если 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;
}
1 голос
/ 10 февраля 2011

не идеально, я признаю, но это работает

мой код:

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

, если кто-то знает что-то более эффективное, пожалуйста, напишите это

0 голосов
/ 10 февраля 2011

В моем 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;
    }

storeUrl печатает путь к базе данных sqlite.

Если вы откроете этот путь с помощью менеджера sqlite, вы сможете увидеть содержимое вашей базы данных sql. Я использую этот SQLite Manager для анализа баз данных sqlite: SQLite Manager

(Вы можете использовать этот метод только на симуляторе)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...