Katedral Pillon
Katedral Pillon

Reputation: 14864

How do I map relationships in Custom NSManagedObject class

I have two entities: Farmer, Livestock. a farmer has a one-to-many relationship with livestocks. So that each farmer may have a name, address, userid, pig set, chicken set, cow set.

I need to create a custom managed object class for farmer as

@interface ManagedFarmer : NSManagedObject

@property (nonatomic, strong) NSString *name;

@property (nonatomic, strong) NSDate *date;

@property (nonatomic, strong) NSString *address;

@property (nonatomic, strong) NSNumber *userid;

@property (nonatomic, strong) NSArray *cows;//? set of cows: relationship to Livestock entity, designated cows

@property (nonatomic, strong) NSArray *chickens;//? 1-to-many relationship to Livestock entity, designated as chickens: 
@property (nonatomic, strong) NSArray *pigs;

Upvotes: 0

Views: 643

Answers (3)

Konsol Labapen
Konsol Labapen

Reputation: 2434

The following link has a basic tutorial for doing what you are asking: http://code.tutsplus.com/tutorials/core-data-from-scratch-subclassing-nsmanagedobject--cms-21880

Upvotes: 0

quellish
quellish

Reputation: 21244

"NSArray the correct way to represent the relationship data?"

NSSet is used to model relationships in an NSManagedObject subclass. NSArray is used for fetched properties, which are a kind of weak relationship.

Typically you would use the Core Data Model Editor built into Xcode to modify your model, and then have Xcode generate the NSManagedObject subclass files as a template for you to work with. This would automatically generate NSSet properties for relationships (but, sadly, will not automatically generate properties for fetched properties ).

"when I fetch a farmer by userid, does cascading automatically occur such that I also get all the Livestock entities belonging to this farmer for free?"

When objects are fetched their relationships are "faults". The object graph will only have placeholders for the objects at the target of the relationship until they are accessed. This helps limit the size of the in-memory object graph, and is something that Core Data is very good at. You can choose to include the targets of relationships in a fetch by setting the appropriate relationship key paths for fetching on your fetch request using setRelationshipKeyPathsForPrefetching:.

Upvotes: 0

Justin Holman
Justin Holman

Reputation: 852

So a NSManagedObject is used in conjunction with Core Data. Create your model, create the relationships in that model and then have Xcode create your NSManagedObject classes for you.

Upvotes: 1

Related Questions