Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a property reference to an NSManagedObject unsafe?

Tags:

ios

core-data

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.

like image 248
JRG-Developer Avatar asked Dec 18 '13 23:12

JRG-Developer


1 Answers

There is no reason to avoid using the managed object directly, provided that:

  • You only use the managed object with a single managed object context, and
  • You either
    • only ever use the managed object on a single thread or queue, or
    • Make sure to use 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.

like image 153
Tom Harrington Avatar answered Nov 16 '22 19:11

Tom Harrington