[UINavigationController setManagedObjectContext:]: 无法识别的选择器发送到实例

[UINavigationController setManagedObjectContext:]: unrecognized selector sent to instance

我知道这个问题已经被问过很多次了,但这些答案无助于解决我的问题。

首先,我正在使用 CoreData 制作一个基于选项卡的应用程序,它会在按下 TableViewController 按钮时打开。

main.storyboard 文件以防万一: http://www.pictureupload.de/originals/pictures/200215153130_Screen_Shot_2015-02-20_at_15.24.09.png

一切正常,并将数据保存到数据库中,但是如果我尝试在 TableViewController 中显示它们,它会突然崩溃 (-[UINavigationController setManagedObjectContext:]: 无法识别的选择器发送到实例 0x79092b80)。

AppDelgate.m 只是从核心数据预设中复制和粘贴。 以防万一:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}

#pragma mark - Core Data stack


- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "controwl.a" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
    return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"trackingData" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

// Create the coordinator and store

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"timetracking.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
    // Report any error we got.
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
    dict[NSLocalizedFailureReasonErrorKey] = failureReason;
    dict[NSUnderlyingErrorKey] = error;
    error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
    // Replace this 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.
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
    return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
    return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
    NSError *error = nil;
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&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.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}
}

@end

TableViewController 由 FirstViewController 通过 btnBarAdd 函数调用:

FirstViewController.m

@implementation FirstViewController

@synthesize context = _context;

- (void)viewDidLoad {
[super viewDidLoad];

_context = [(AppDelegate*)[[UIApplication sharedApplication]delegate] managedObjectContext];

}

- (IBAction)btnBarAdd:(id)sender {

[self performSegueWithIdentifier:@"FirstTableViewSegue" sender:sender];

}



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

if ([[segue identifier] isEqualToString:@"FirstTableViewSegue"]) {

    [[segue destinationViewController] setManagedObjectContext:_context];

}
}
@end

感谢任何帮助!

重置模拟器并再次运行。

您可能已经向实体添加了新属性,每次更改核心数据实体时都应删除该应用程序。

检查你的代码是否有目标视图控制器

[[segue destinationViewController] setManagedObjectContext:_context];

有属性 或方法来分配上下文。好像你正在用 segue 调用 UINavigationController 但它没有这样的 属性 来处理上下文

segue 链接 FirstViewController 到 Navigation Controller,因此 segue 的 destinationViewControllerUINavigationController。因此,当您尝试在 destinationViewController 上设置 managedObjectContext 时,您会收到错误消息。

您需要使用导航控制器的 topViewController 属性 来访问 FirstTableViewController 本身:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"FirstTableViewSegue"]) {
        UINavigationController *navCtrl = (UINavigationController *)[segue destinationViewController];
        // Assuming the class of your table view controller is "FirstTableViewController"....
        // You will need to import the relevant .h file
        FirstTableViewController *tableVC = (FirstTableViewController *)navCtrl.topViewController;
        [tableVC setManagedObjectContext:_context];
    }
}