无法将NSManagedObjectContext传递到我的视图控制器 [英] Unable to pass NSManagedObjectContext to my view controller

查看:79
本文介绍了无法将NSManagedObjectContext传递到我的视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我可能在我的头上,但怀疑我缺少一些相当根本的东西。我已经搜索堆栈和其他论坛寻求解决方案的帮助。我试过所有的解决方案,我发现,但没有工作,我的情况,我看不到我失踪了。



我创建了一个CoreData应用程序。所有在使用我的appDelegate中的NSManagedObjectContext读取和写入数据到CoreData存储。我已经检查,看看NSManagedObjectContext是否设置在我的AppDelegate,它是。在传递给我唯一的viewController后,我检查它是否设置,它不是。这显然是我的问题。我试过一切,不能解决的解决方案,现在累了,想睡觉。我是iOS的新手,所以我确定它是一些基本的东西。



这是我的代码。



AppDelegate.m

  #importAppDelegate.h
#importViewController.h
#importRecipe.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(@有一个错误!
}

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

viewController.managedObjectContext = self.managedObjectContext;

//应用程序启动后覆盖自定义点。
return YES;
}

#pragma mark - 核心数据

- (NSManagedObjectModel *)managedObjectModel
{
if(managedObjectModel == nil){
NSString * modelPath = [[NSBundle mainBundle] pathForResource:@RecipeBookofType:@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 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

  #importViewController.h
#importRecipe.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(@有一个错误!
}

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

我知道NSManagedObjectContext是nil在我的ViewController。问题是我如何将我的上下文从AppDelegate传递到ViewController?我不想从我的viewControllers(更多的希望可以添加)问我的AppDelegate每次我想查询CoreData,我想通过managedObjectContext。



我希望一切都有意义。 :)

解决方案

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



我使用的是:

 code> viewController.managedObjectContext = self.managedObjectContext; 

当我应该使用:

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

感谢user523234把我放在正确的行上。


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. :)

解决方案

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.

这篇关于无法将NSManagedObjectContext传递到我的视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆