无法从另一个视图控制器访问核心数据中的实体

时间:2015-03-31 16:13:40

标签: objective-c core-data uiviewcontroller

我是一名新手Objective-C程序员和核心数据用户。这是我第一次使用核心数据。我想要做的是将实体放在核心数据库中,然后在另一个View Controller中检索和编辑它们 这是我的ViewController.m中的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];

    NSString *documentName = @"myDocument";
    NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
    UIManagedDocument *document = [[UIManagedDocument alloc]initWithFileURL:url];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path] ];
    if(fileExists)
    {
        [document openWithCompletionHandler:^(BOOL success){
            if(!success) NSLog(@"Error (this isn't printed)");
        }];
    }
    else
    {
        [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
            if(!success) NSLog(@"Error (this isn't printed)");
        }];

        NSManagedObjectContext *context = document.managedObjectContext;

        QuestionResponse *question1 = [NSEntityDescription insertNewObjectForEntityForName: @"QuestionResponse" inManagedObjectContext: context];
        QuestionResponse *question2 = [NSEntityDescription insertNewObjectForEntityForName: @"QuestionResponse" inManagedObjectContext: context];
        QuestionResponse *question3 = [NSEntityDescription insertNewObjectForEntityForName: @"QuestionResponse" inManagedObjectContext: context];
        QuestionResponse *question4 = [NSEntityDescription insertNewObjectForEntityForName: @"QuestionResponse" inManagedObjectContext: context];

        question1.question = @"What is your favorite food?";
        question2.question = @"Who is your favorite fictional character?";
        question3.question = @"Name someone who loves you:";
        question4.question = @"What is your favorite place (real or fictional)?";

        question1.order = [NSNumber numberWithInt:1];
        question2.order = [NSNumber numberWithInt:2];
        question3.order = [NSNumber numberWithInt:3];
        question4.order = [NSNumber numberWithInt:4];
        question1.group = [NSNumber numberWithInt:1];
        question2.group = [NSNumber numberWithInt:1];
        question3.group = [NSNumber numberWithInt:2];
        question3.group = [NSNumber numberWithInt:2];
        question1.display = [NSNumber numberWithBool:NO];
        question2.display = [NSNumber numberWithBool:NO];
        question3.display = [NSNumber numberWithBool:NO];
        question4.display = [NSNumber numberWithBool:NO];

        NSFetchRequest* request2 = [NSFetchRequest fetchRequestWithEntityName:@ "QuestionResponse"];
        NSError* error2 = nil;
        NSArray* results = [context executeFetchRequest:request2 error:&error2];
        if (!results || !results.count){
            NSLog(@"No elements (this isn't printed)");
        }
        if(results.count == 4)
        {
            NSLog(@"We have four entities (this is what is printed)");
        }        
    }
}

在我的AnswerViewController.m中,这是代码:

 - (IBAction)answerQuestion1:(id)sender {    
    //File creation begins here (same as in View Controller)
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSString *documentName = @"myDocument";    
    NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
    UIManagedDocument *document = [[UIManagedDocument alloc]initWithFileURL:url];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path] ];
    if(fileExists)
    {
        [document openWithCompletionHandler:^(BOOL success){
            if(!success) NSLog(@"Error");
        }];
        NSLog(@"File Exists (this is printed)");
    }
    else
    {
        [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
            if(!success)NSLog(@"There has been a problem (this isn't printed)");
        }];
    }
    NSManagedObjectContext *context = document.managedObjectContext;
    //File Creation ends here

    NSError *error = nil;

    NSFetchRequest* request2 = [NSFetchRequest fetchRequestWithEntityName:@ "QuestionResponse"];
    NSError* error2 = nil;
    NSArray* results = [context executeFetchRequest:request2 error:&error2];
    if (!results || !results.count){
        NSLog(@"No entities (this is what is printed");
    }
    else
    {
        NSLog(@"Some entities (this isn't printed)");
    }
}

在我的ViewController.m中,核心数据有四个元素但是当我尝试在AnswereViewController.m中访问它们时,核心数据中没有任何内容。为什么会发生这种情况?如何从AnswereViewController.m访问我的元素?

1 个答案:

答案 0 :(得分:0)

为了成功使用CoreData,您必须先了解它的流程。从本质上讲,CoreData可以分为两个主要部分:

  1. 数据库(所以.sqlite文件本身)
  2. 持久性商店协调员(以下称为psc)
  3. 到目前为止,您在ViewController.m中所做的是您告诉编译器将4个对象插入到managedObjectContext中。这是在psc级别完成的。对于所有数据库更改,psc就像一个暂存器。直到你实际告诉它保存它,它只会存在于psc而不是你的.sqlite文件中。你需要做的是打电话:

    [context save:&error2]
    

    这将告诉编译器将您当前的psc状态推送到数据库中,以便它继续存在。

    我希望这会对你有所帮助。