How to store CGRect and other things in core data

Viewed 6717

I'm having a few teething problems with coredata, but feel it would clear things up for me greatly if someone could explain some simple cases to me.

I want to put my model into coredata, and at a most simple case take advantage of undo/redo. Thing is, all the examples I see tend to store either strings or integers. What if I have a class as follows that I wanted to implement in core data (a made up example):

@interface Badge : NSObject {

NSString *textForBadge;
int      badgeValue;
UIColor  *color;
CGRect    rect;
NSMutableArray *awards; // this would be a list of 'Category' - another custom class
}

These are all made up on the spot, but each highlight a confusion

As I see it, I would open the .xcdatamodel and add a new Entity caled 'Badge', which would be an NSManagedObject. I then add a property for textForBadge of type String. So far so good. I do somthing similar for badgeValue, but then come to the UIColor and CGRect and I'm a bit stumped, since there isn't a property for those. Am I supposed to create an entity to represent each (i.e a Rect entity that has four properties x,y,w,h) that are ints? Then populate a CGRect with these ints each time? Ditto for the UIColor?

Finally, I come to my list of awards. If these are a list of pointers to a number of objects representing an award they might contain an image, a colour, text etc. I assume that award would again be an entity I have to design and rather than Badge storing an array I would have a 1 to many relationship from it to the Award class.

Am I getting any of this right, or going in the compete opposite direction? All the examples I see operate on vanilla objects like String or int so want to make sure I have this right in my head before implementing a bunch of stuff.

Kind regards,

Bryn

4 Answers

Storing UIColor objects and structures like CGRect in Core Data is fairly easy (this may be new since the OP asked about it):

Define the objects as Transformable in your model:

snapshot of Core Data model

In the NSManagedObject classes define and use UIColor objects normally:

@property (nonatomic, retain) UIColor *foreground;

textView.textColor = element.foreground;

Wrap CGRect structures in an NSValue object:

@property (nonatomic, retain) NSValue *imageRect;

CGRect imageRect = [self.imageRect CGRectValue];
imageRect.size.width = 100;
self.imageRect = [NSValue valueWithCGRect:imageRect];
Related