I have subclassed NSManagedObjects for a Person and an Company. In core data, I have set these up with a two way relationship (one from person to company called personCompany, one the other way around companyPerson). My App saves both a Person and a Company beautifully, their header files look as follows (massively simplified for demo purposes):
#import <CoreData/CoreData.h>
@interface BBPerson : NSManagedObject
@property (nonatomic) NSString *firstName;
@property (nonatomic) NSString *lastName;
@end
----------------------
#import <CoreData/CoreData.h>
@interface BBCompanyName : NSManagedObject
@property (nonatomic) NSString *companyName;
@end
In my "Add Person" view controller, part of the save method is below.
//If this is a new person, best add a person
if (!currentPerson) {
currentPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person"
inManagedObjectContext:managedObjectContext];
}
//Write the values back to the entity
currentPerson.firstName = txtFirstName.text;
currentPerson.lastName = txtLastName.text;
**//I WANT TO DO THE BELOW: but clearly can't**
//[currentPerson setCompany:selectedCompany];.
//Save back to core data
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(@"Failed to save - error: %@", [error localizedDescription]);
}
If I had another Company referenced here (show above as selectedCompany), how can I change my subclassed NSManagedObject to add this relationship? I have looked at the documentation and I am still a bit adrift.
What I am trying to do, with my subclassed NSManagedObject is to create a relationship that can be persisted. Something like [currentPerson setCompany:selectedCompany]; which would of course require on the currentPerson a method - how would this method look?
What I would like to do is be able to at a later stage in the app is to call all the People back for a Company. I did think about doing this using predicates and foreign keys and ditch relationships, but that is me getting myself in the wrong mindset that this is a database, which it is not.
@property (nonatomic) BBCompany *company;on the BBPerson header? Then set it to dynamic in the implementation? And critically will that give core data enough information to persist this? Ta again - MagicalArmchair