RJ168
RJ168

Reputation: 1046

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.

Upvotes: 1

Views: 132

Answers (2)

user2068378
user2068378

Reputation: 114

you can fetch related company name by relation name.

User userObj=(User)[selectedData objectAtIndex:indexPath.row];

NSString *companyName = userObj.RELATION_NAME.company_name

RELATION_NAME is used to connect from user entity to company entity.

Hope this will help.

Upvotes: 0

jrturton
jrturton

Reputation: 119242

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.

Upvotes: 1

Related Questions