-->

Unable to pass NSManagedObjectContext to my view c

2020-08-01 05:18发布

问题:

Ok, I may be in well over my head here, but suspect I am missing something quite fundamental. I have searched on stack and other forums for help on finding a solution. I've tried all the solutions I have found but none work for my situation and I cannot see what I am missing.

I have created a CoreData app. All works fine in reading and writing data to the CoreData store using NSManagedObjectContext within my appDelegate. I have checked to see if the NSManagedObjectContext is set in my AppDelegate and it is. After passing it to my only viewController I check to see if it is set and it isn't. So that is clearly my issue. I have tried everything and cannot fathom the solution, now tired and want to go to bed. I'm pretty new to iOS, so I am sure it's something fundamental.

Here's my code as it stands.

AppDelegate.m

#import "AppDelegate.h"
#import "ViewController.h"
#import "Recipe.h"

@interface AppDelegate()

@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, strong) ViewController *viewController;
@end

@implementation AppDelegate 

@synthesize managedObjectModel, managedObjectContext, persistentStoreCoordinator, viewController;

@synthesize window = _window;

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

    NSManagedObjectContext *context = [self managedObjectContext];
    if (!context) {
        NSLog(@"There is an error!!!");
    }

    if (context == nil) {
        NSLog(@"Context is nil in appdelegate");
    } 
    else {
    NSLog(@"Context is set in appdelegate"); 
    }

    viewController.managedObjectContext = self.managedObjectContext;

    // Override point for customization after application launch.
    return YES;
}

#pragma mark - Core Data

- (NSManagedObjectModel *)managedObjectModel
{
    if (managedObjectModel == nil) {
        NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"RecipeBook" ofType:@"momd"];
        NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
        managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    }
    return managedObjectModel;
}

- (NSString *)documentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

- (NSString *)dataStorePath
{
    return [[self documentsDirectory] stringByAppendingPathComponent:@"DataStore.sqlite"];
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (persistentStoreCoordinator == nil) {
        NSURL *storeURL = [NSURL fileURLWithPath:[self dataStorePath]];

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

        NSError *error;
        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
            NSLog(@"Error adding persistent store %@, %@", error, [error userInfo]);
            abort();
        }
    }
    return persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (managedObjectContext == nil) {
        NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
        if (coordinator != nil) {
            managedObjectContext = [[NSManagedObjectContext alloc] init];
            [managedObjectContext setPersistentStoreCoordinator:coordinator];
        }
    }
    return managedObjectContext;
}
@end

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UITableViewController {
NSArray *recipes;
NSManagedObjectContext *managedObjectContext;
}

@property (nonatomic, retain) NSArray *recipes;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@end

ViewController.m

#import "ViewController.h"
#import "Recipe.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize recipes;
@synthesize managedObjectContext;

- (void)viewDidLoad
{
[super viewDidLoad];

NSLog(@"View Did Load");

NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
    NSLog(@"There is an error!!!");
}

if (context == nil) {
    NSLog(@"Context is nil in viewController");
} 
else {
    NSLog(@"Context is set in viewController"); 
    }

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
    return YES;
    }
}

- (void)viewDidUnload {
[super viewDidUnload];
}

@end

I know the NSManagedObjectContext is nil in my ViewController. The question is how do I pass my context from AppDelegate into ViewController? I don't want to have to question the AppDelegate from my viewControllers (More will hopefully be added) every time I want to query CoreData, I'm looking to pass the managedObjectContext around.

I hope that all makes sense. :)

回答1:

I have discovered the answer to my issue. The managedObjectContext wasn't being passed correctly to my viewController.

I was using:

viewController.managedObjectContext = self.managedObjectContext;

When I should have been using:

ViewController *viewController = (ViewController *)self.window.rootViewController;
viewController.managedObjectContext = self.managedObjectContext;

Thanks user523234 for putting me on the right lines.