0

So I have two view controllers. View controller A segues to view controller B. In prepareForSegue in view controller A, it creates a new managed object context and assigns my global UIManagedDocument context as the parent context. I then create a new managed object using the child context and assign it to a strong property of view controller B.

As soon as viewDidLoad finishes in view controller B, the managed object is still valid (which is what I expect), but the managed object context for this new object gets set nil.

I know the variable *context below goes out of scope at the end of prepareForSegue, but I would expect for the global parent context to retain the child context, or the managed object to retain the context itself.

Here is a very slightly modified version of my code for prepareForSegue in view controller A.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UIViewController *vc = segue.destinationViewController;

    if ([vc isKindOfClass:[ViewControllerB class]]) {

        // Create new context and assign its parent
        NSManagedObjectContext *mainContext = [myGlobalUIManagedDocument managedObjectContext];
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        context.parentContext = mainContext;

        // Create new managed object using the context
        NSManagedObject *objectB = [NSEntityDescription insertNewObjectForEntityForName:@"ObjectB" inManagedObjectContext:context];

        // Pass the object to the destination view controller
        ViewControllerB *vcB = (ViewControllerB *)vc;
        vcB.strongManagedObjectProperty = objectB;
    }
}

Now to my best knowledge none of the code in view controller B is setting the context to nil. I just would like to know, if from the information I have given, that the managed object context for *objectB should still be non-nil as soon as prepareForSegue loses scope. If so, I've some more debugging to do it seems.

UPDATE: I was able to track the exact moment my contexts gets set to nil as sometime after viewWillAppear and before viewDidAppear in view controller B. I am totally confused.

4

1 に答える 1

0

私は実際にここで何が起こっているのか理解していませんでした。

私の解決策は、UIManagedDocumentを管理するeditingContextというシングルトンクラスにUIManagedObjectContextプロパティを作成することでした。UIManagedDocumentのメインコンテキストの子としてコンテキストを作成し、それを独自のプロパティに格納する役割を果たします。

そのため、ビューコントローラBに渡すたびにコンテキストがnilに設定されることはありません。コンテキストが終了したら、checkinContext:メソッドをシングルトンに送信して編集コンテキストを解放します。

一種のハックですが、すべてのセグエでこのメソッドを使用して、ユーザーがアクションをキャンセルした場合に破棄できる「スクラッチ」コンテキストを持つという利点を得ることができます。

于 2013-02-21T14:36:39.447 に答える