NSManagedObject's managedObjectContext property is nil

后端 未结 2 689
执念已碎
执念已碎 2021-01-18 07:44

I\'m trying to create a temporary managed object context, and after a few screens of the user putting in information, I merge that context with the main context (to ensure t

相关标签:
2条回答
  • 2021-01-18 08:11

    I recently ran into the same problem again, although it was in a different situation. I needed a temporary managed object context, completely separate from the main one, but I again ran into the problem of it disappearing after it goes out of scope. This time I decided to investigate further, and I ultimately realized that managedObjectContext is not a property of NSManagedObject, but a method. This means one of two things:

    1. If it uses a property in the underlying implementation, that property will not hold a strong reference to the context
    2. If the managed object context is derived in some other way, it will also not hold a strong reference to that context.

    In either case, the context has no strong references, goes out of scope, and the NSManagedObjects have a nil managedObjectContext.

    The solution was to simply keep the context around by creating a strong property for it.

    0 讨论(0)
  • 2021-01-18 08:12

    I do not see why you would need a second managed object context. IMHO, you are introducing complexity into your app that does not serve any particular purpose.

    Insert the new object into the main context. Let the user input his data. If he breaks off, simply call

    [managedObjectContext rollback];
    

    or, if the user finishes and all the data is validated, call

    [managedObjectContext save:nil];
    
    0 讨论(0)
提交回复
热议问题