In the book Learning Core Data for iOS, the author creates several UIViewControllers
which each have a property that refers to an NSManagedObjectID
.
In example,
@interface LocationAtShopViewController : UIViewController
@property (strong, nonatomic) NSManagedObjectID *selectedObjectID;
// ... other properties and methods
@end
In this manner, he is able to pass an NSManagedObjectID
from one controller to another and retrieve the associated NSManagedObject
object using NSManagedObjectContext
's existingObjectWithID:error:
method.
Further, he doesn't ever set an NSManagedObject
object directly (even if he already has a variable reference to it), nor does he keep a reference to the NSManagedObject
object very long (instead, he retrieves it in each method that he needs it).
Is it unsafe (i.e. will cause crashes or lead to unexpected behavior in certain circumstances) to pass an NSManagedObject
directly between controllers via a property reference, or simply keep a reference to it on a controller?
In example,
@interface LocationAtShopViewController : UIViewController
@property (strong, nonatomic) LocationAtShop *locationAtShop;
// ... other properties and methods
@end
Assuming a single, shared NSManagedObjectContext
is used, so disregard issues caused by passing between multiple contexts, which isn't safe in general.
There is no reason to avoid using the managed object directly, provided that:
performBlock
or performBlockAndWait
when working on a different queue.Keeping only the object ID may be less error-prone since it makes it a lot harder to accidentally mix up contexts or queues. That may make it a better idea for less experienced developers, who are therefore less likely to screw things up. But it's certainly not wrong nor even especially dangerous to keep the object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With