无法将NSManagedObjectContext传递给我的视图控制器

时间:2012-02-19 00:23:46

标签: ios cocoa-touch ios5 nsmanagedobjectcontext

好吧,我可能在这里很好,但怀疑我错过了一些非常基本的东西。我已经在堆栈和其他论坛上搜索了寻求解决方案的帮助。我已经尝试了我找到的所有解决方案,但没有适用于我的情况,我看不出我错过了什么。

我创建了一个CoreData应用。所有这些都可以在我的appDelegate中使用NSManagedObjectContext读取和写入数据到CoreData商店。我已经检查过是否在我的AppDelegate中设置了NSManagedObjectContext,它是。将它传递给我唯一的viewController之后,我检查它是否已设置但不是。所以这显然是我的问题。我已经尝试了一切,无法理解解决方案,现在累了,想要去睡觉。我对iOS很陌生,所以我相信它是基本的东西。

这是我的代码。

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

我知道我的ViewController中的NSManagedObjectContext是nil。问题是如何将我的上下文从AppDelegate传递到ViewController?每次我想查询CoreData时,我都不想从我的viewControllers(希望会添加更多内容)中对AppDelegate提出疑问,我想要传递managedObjectContext。

我希望一切都有道理。 :)

1 个答案:

答案 0 :(得分:1)

我发现了我的问题的答案。 managedObjectContext未正确传递给我的viewController。

我正在使用:

viewController.managedObjectContext = self.managedObjectContext;

当我应该使用时:

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

感谢user523234让我走上正确的路线。