Search code examples
ioscore-dataentity-relationship

Fetching data with relationship in core data


I am using core data framework and want to fetch the data using relationship. I have 2 entities named User and Company having user_name and company_name field's. I also have relationship to-many name rel_user->user.

Now I am trying to fetch data like this

User *userObj=(User*)[selectedData objectAtIndex:indexPath.row];
NSSet *resultData = [userObj valueForKeyPath:@"rel_user.user"];
    NSLog(@"subject -> %@",[resultData description]);

I want to show the company name related to user.


Solution

  • What is the name of the inverse relationship to rel_user? Assuming it's rel_company and the user -> company relation is to-one, you'd just use

    user.rel_company.company.name
    

    Where user is a particular User object.

    There isn't really any benefit to specifically naming your relationships rel-something. It reads much nicer to have a company relationship on the User (since it will be a property holding the Company) and a users relationship on the Company. You can then tell from the name what the property will contain and if it is a to-one or to-many relationship.