Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData transient relationship example

Does anybody have an example on how to model and code a transient to-one relationship in CoreData? For example, I have 2 entities with a one-to-many relationship. Doctor and Appointment. Now I want an transient relationship called mostRecentAppointment on the doctor entity. It's straightforward to model in the xcode designer, but I'm not sure about the implementation side. Also should I implement an inverse? Seems silly.

like image 642
batkuip Avatar asked Apr 29 '13 13:04

batkuip


2 Answers

Have a look at this code I wrote recently, to cache an image in an NSManagedObject:

First you define a transient property in your model (notice that if your transient property points to an object type other than those supported by CoreData you'll leave as "Undefined" in the model)

enter image description here

Then, you re-generate your NSManagedObject subclass for that entity or just add the new property manually, the header file should look like this:

@interface Card : NSManagedObject

@property (nonatomic, retain) NSString * imagePath;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * order;
@property (nonatomic, retain) NSString * displayName;
@property (nonatomic, retain) UIImage *displayImage;

@end

Here we change the class of the transient property to the actual class type

e.g. displayImage type here is UIImage.

In the implementation file (or an extension class) you implement the getter/setter for your transient property:

-(UIImage*)displayImage{

  //Get Value
  [self willAccessValueForKey:@"displayImage"];
  UIImage *img = (UIImage*)[self primitiveValueForKey:@"displayImage"];
  [self didAccessValueForKey:@"displayImage"];

   if (img == nil) {
    if ([self imagePath]) { //That is a non-transient property on the object
      img = [UIImage imageWithContentsOfFile:self.imagePath];
      //Set Value
      [self setPrimitiveValue:img forKey:@"displayImage"];
    }
  }
  return img;
}

Hope that helps you.

like image 120
Mariam K. Avatar answered Sep 22 '22 11:09

Mariam K.


What you need to do is add an entity of type Appointment called newAppointment and set this each time you create a new appointment for a given doctor. Its that simple.

Always implement an inverse as apple recommend this for validation and core data efficiency.

Alternatively you could timestamp the appointments and use NSPredicates to search for the latest appointment in a given Doctor's linked appointments.

like image 25
Dev2rights Avatar answered Sep 24 '22 11:09

Dev2rights