Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 这是使用CoreData NSFetchedResults和NSPersistentStore函数的正确方法吗?_Ios_Core Data_Nsfetchedresultscontroller - Fatal编程技术网

Ios 这是使用CoreData NSFetchedResults和NSPersistentStore函数的正确方法吗?

Ios 这是使用CoreData NSFetchedResults和NSPersistentStore函数的正确方法吗?,ios,core-data,nsfetchedresultscontroller,Ios,Core Data,Nsfetchedresultscontroller,我一直在尝试将预填充的数据库加载到我的设备中,我尝试从模拟器目录复制数据库并将其放置到我的应用程序文件夹中,但它不起作用,所以我想知道我的NSFetchedResultsController是否正确读取 - (NSFetchedResultsController *)fetchedResultsController { if (fetchedResultsController_ != nil) { return fetchedResultsController_;

我一直在尝试将预填充的数据库加载到我的设备中,我尝试从模拟器目录复制数据库并将其放置到我的应用程序文件夹中,但它不起作用,所以我想知道我的NSFetchedResultsController是否正确读取

- (NSFetchedResultsController *)fetchedResultsController {

    if (fetchedResultsController_ != nil) {
        return fetchedResultsController_;
    }

    CoreDataMelakaAppDelegate *appDelegate = (CoreDataMelakaAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"WhereTo" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
   // [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    NSError *error = nil;
    if (![fetchedResultsController_ performFetch:&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.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return fetchedResultsController_;
}    
持久存储

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataMelaka.sqlite"];

    NSError *error = nil;
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil 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 the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return persistentStoreCoordinator_;
}
我用这个替换了persistentStore,现在无论我如何从模拟器中删除数据库或应用程序,它都会显示2个数据,这是我第一次尝试此方法时安装的

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"CoreDataMelaka.sqlite"];

    NSString *storePath = [[NSBundle mainBundle] pathForResource:@"CoreDataMelaka" ofType:@"sqlite"];


    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataMelaka.sqlite"]; 

    NSLog(@"store URL %@", storeURL);

    // Put down default db if it doesn't already exist
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:writableDBPath]) {
        NSLog(@"proceed");
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"CoreDataMelaka" ofType:@"sqlite"];
        NSLog(@"doesnt exist");
        NSLog(@"defalultStorePath %@", defaultStorePath);


        if (defaultStorePath) {
            [fileManager copyItemAtPath:defaultStorePath toPath:writableDBPath error:NULL];
            NSLog(@"storePath= %@", storePath);
        }
    }    

    NSError *error = nil;
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return persistentStoreCoordinator_;
}

NSFetchedResultsController看起来像是标准的自动生成代码。它应该是正确的抓取,但我需要了解更多关于您的代码,以100%确定

我猜问题与找到数据库有关。您确定要将其放在文档目录中吗?我假设您已将数据库复制到Xcode中,它正在将数据库复制到应用程序中。如果是这种情况,您的数据库将不在文档目录中。您可以使用Xcode中Organizer的设备部分下载应用程序文件以确认这一点。您的数据库正在复制到主捆绑包中,您需要从主捆绑包中提取它。这里有一些代码可以做到这一点:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (__persistentStoreCoordinator != nil)
        return __persistentStoreCoordinator;

    NSError * error = nil;
    NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Store.sqlite"];
    NSFileManager * fileManager = [NSFileManager new];

    // !!!: Be sure to create a new default database if the MOM file is ever changed.

    // If there is no previous database, then a default one is used.
    if (![fileManager fileExistsAtPath:storePath]) {

        NSURL * defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"DefaultStore.sqlite" 
                                                          withExtension:nil];

        // Copies the default database from the main bundle to the documents directory.
        [fileManager copyItemAtURL:defaultStoreURL
                             toURL:storeURL
                             error:&error];

        if (error) {

            // Handle error here.

            // Resets the error.
            error = nil;
        }
    }

    [fileManager release];

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

    [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                           configuration:nil 
                                                     URL:storeURL 
                                                 options:nil 
                                                   error:&error];
    if (error) {

        // Handle error here.

        abort();
    }    

    return __persistentStoreCoordinator;
}

要查找此和其他核心数据便利,请查看。

您的NSFetchedResultsController看起来像是标准的自动生成代码。它应该是正确的抓取,但我需要了解更多关于您的代码,以100%确定

我猜问题与找到数据库有关。您确定要将其放在文档目录中吗?我假设您已将数据库复制到Xcode中,它正在将数据库复制到应用程序中。如果是这种情况,您的数据库将不在文档目录中。您可以使用Xcode中Organizer的设备部分下载应用程序文件以确认这一点。您的数据库正在复制到主捆绑包中,您需要从主捆绑包中提取它。这里有一些代码可以做到这一点:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (__persistentStoreCoordinator != nil)
        return __persistentStoreCoordinator;

    NSError * error = nil;
    NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Store.sqlite"];
    NSFileManager * fileManager = [NSFileManager new];

    // !!!: Be sure to create a new default database if the MOM file is ever changed.

    // If there is no previous database, then a default one is used.
    if (![fileManager fileExistsAtPath:storePath]) {

        NSURL * defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"DefaultStore.sqlite" 
                                                          withExtension:nil];

        // Copies the default database from the main bundle to the documents directory.
        [fileManager copyItemAtURL:defaultStoreURL
                             toURL:storeURL
                             error:&error];

        if (error) {

            // Handle error here.

            // Resets the error.
            error = nil;
        }
    }

    [fileManager release];

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

    [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                           configuration:nil 
                                                     URL:storeURL 
                                                 options:nil 
                                                   error:&error];
    if (error) {

        // Handle error here.

        abort();
    }    

    return __persistentStoreCoordinator;
}

要查找此和其他核心数据便利,请查看。

您的预填充数据库是由CoreData创建的还是您自己创建的?我使用模拟器使用核心数据创建预填充数据库。它存储在模拟器中,但当我复制特定数据库并将其粘贴到应用程序文件夹时,它会在模拟器中创建另一个新数据库,该数据库为空,并读取到,不是应用程序文件夹中的1,而是由CoreData创建的预填充数据库,还是您自己创建的?我使用模拟器使用核心数据创建预填充数据库。它存储在模拟器中,但当我复制该特定数据库并将其粘贴到应用程序文件夹时,它会在模拟器中创建另一个新数据库,该数据库为空,并读取该数据库,而不是应用程序文件夹中的1。Yeap,我从user/library/application support/iphone simulator/4.3.2/applications//Documents获取数据库。。我不理解文件下载部分,使用设备部分,izzit一旦我连接了设备,在组织者部分,我从目录手动下载它?如果我将其上传到应用商店,数据库将不会遵循rite?您可能是从模拟器上的文档中复制它,但当您通过Xcode将其复制到应用程序中时,它将进入主捆绑包。要从设备下载文件,请打开管理器,选择设备选项卡,选择设备下的应用程序,选择应用程序,然后选择下载。顺便说一下,我使用的是Xcode 4。下载文件后,您应该会看到默认数据库位于主捆绑包中。通过将数据库放入主捆绑包,它将被上传到应用商店。如果这不是您想要的,那么您需要在存档之前删除它。您可能会发现您的文档目录中有一个数据库,但它应该是为您创建核心数据的空数据库。您可以打开它并运行一些查询来确认这一点。啊哈。因此,使用organizer是构建预填充数据库的方法。我明天第一件事就开始。我在WWDC的视频中看到了这种方法。谢谢希望它能起作用,hahaWWDC 2011年第317次会议详细讨论了组织者。此外,如果您为数据库创建了一个捆绑包,则需要更改上述代码以转到该捆绑包,而不是主捆绑包。是的,我从user/library/application support/iphone simulator/4.3.2/applications//Documents获取数据库。。我不理解文件下载部分,使用设备部分,izzit一旦我连接了设备,在组织者部分,我从目录手动下载它?如果我将其上传到应用商店,数据库将不会遵循rite?您可能是从模拟器上的文档中复制它,但当您通过Xcode将其复制到应用程序中时,它将进入主捆绑包。要从设备下载文件,请打开管理器,选择设备选项卡,选择设备下的应用程序,选择应用程序,然后选择下载。顺便说一下,我使用的是Xcode 4。下载文件后,您应该会看到默认数据库位于主捆绑包中。通过将数据库放入主捆绑包,它将被上传到应用商店。如果这不是您想要的,那么您需要在存档之前删除它。您可能会发现您的文档目录中有一个数据库,但它应该是为您创建核心数据的空数据库。您可以打开它并运行一些查询来确认这一点。啊哈。因此,使用organizer是构建预填充数据库的方法。我明天第一件事就开始。我在WWDC的视频中看到了这种方法。谢谢希望它能起作用,hahaWWDC 2011年第317次会议详细讨论了组织者。此外,如果您为数据库创建了一个捆绑包,则需要更改上述代码以转到该捆绑包,而不是主捆绑包。