从单独的ViewController访问实体,而不是使用Segues(CoreData)

时间:2014-04-05 01:53:55

标签: ios xcode core-data

我已经了解了一些关于CoreData的知识,我可以从Entity发起的ViewController中正确插入一个新对象,但是我无法从另一个ViewController远程执行。大多数其他示例使用segue来实现它,但我的设置有点不同。它是这样的:

[Master View Controller] -[Modal]-> [Pick View Controller] -[Modal]-> [Input View Controller]. 

我不能简单地使用:

 UINavigationController *navigationController = (id)[segue destinationViewController];

    MySecondViewController *topViewController = [navigationController topViewController];
    topViewController.managedObjectContext = self.managedObjectContext;

完全没有。 代码:

Master View Controller.m:

- (void)setDataItem:(NSString *)name :(NSNumber *)money :(NSDate *)date :(BOOL)dateOwed
{
    if (_money1 != money) {
        _money1 = money;
    }
    if (_date1 != date) {
        _date1 = date;
    }
    if (_name1 != name) {
        _name1 = name;
    }
    if (_dateOwed1 != dateOwed) {
        _dateOwed1 = dateOwed;
    }

    NSManagedObjectContext *context = [self managedObjectContext];
    OweInfo *oweInfo = [NSEntityDescription
                        insertNewObjectForEntityForName:@"OweInfo"
                        inManagedObjectContext:context];
    oweInfo.name = name;
    oweInfo.dateowed = [NSNumber numberWithBool:dateOwed];
    OweDetails *oweDetails = [NSEntityDescription
                              insertNewObjectForEntityForName:@"OweDetails"
                              inManagedObjectContext:context];

    oweDetails.date = date;
    oweDetails.money = money;
    oweDetails.info = oweInfo;
    oweInfo.details = oweDetails;
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }




}


- (IBAction)submit:(id)sender
{
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber * myNumber = [f numberFromString:oField.text];
    MasterViewController *topViewController = [[MasterViewController alloc]init];
    topViewController.managedObjectContext = self.managedObjectContext;

    MasterViewController *master = [[MasterViewController alloc]init];
    [master setDataItem:iField.text :myNumber :dueDate.date :dateOwed];

  [self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}

每次我尝试以上操作时,我都会:

2014-04-04 20:48:45.161 WhatIOwe[3688:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'OweInfo''

2 个答案:

答案 0 :(得分:0)

查找依赖注入并了解该模式,因为这就是你应该在这里做的事情。无论何时创建视图控制器,都需要将对NSManagedObjectContext的引用传递给该新视图控制器。通过这样做,您将始终在需要时提供参考。

答案 1 :(得分:0)

尝试将coreData传递给第二个(或多个)viewControllers时出现错误。这个站点告诉我在调用managedObjectContext之前调用了viewDidLoad。在[super viewDidLoad]之后添加此代码; :

id delegate = [[UIApplication sharedApplication] delegate]; context = [delegate managedObjectContext];

我能够在多个viewControllers中使用核心数据。