开发者

How do I access the relationship name of a Core Data parent object?

I have a simple Core Data iPhone app where Parents have a one-to-many relationship with Children. In the first view, you are presented with a list of Parents; tapping on one provides the corresponding list of Children. In the Child view, I want the each cell to show the Child name, and then开发者_StackOverflow社区 the Parent name as a subtitle. I have used the following command:

cell.detailTextLabel.text = [[managedObject valueForKey:@"Parent"] description];

But instead of getting the parent name, the subtitle displays something like:

<Parent: 0x4d5a520> (entity: Parent; id...

Obviously I'm printing out the actual relationship, rather than the object's name. How can I show the actual Parent name ("Mr Smith")?

Thanks.


I managed to work it out! I'm gradually getting the hang of this programming thing... :-)

I'll leave the answer here in case someone else searches for it one day...

Instead of using a generic NSManagedObjectContext with KVC, I used my own subclass:

Child *child = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [child.name description];
cell.detailTextLabel.text = [child.parent.name description];


Your basic problem is that description is a method of NSObject that returns a description useful for programmers. If you have an attribute called description then it will collide with the built-in description method. You may have been confused because when you call description on a NSString, you get the string but if you call any other class, you don't get the literal data e.g. When you call description on a managed object you get the object UUID, whether it is a fault or not, it's attributes and the objects it's related to. All that is useless for anything but debugging.

Never use description as an attribute name and never use the return of description for anything the user ever sees.

If you have a tableview of Child objects as described above then your fetched results controller will return a managed object configured to the Child entity. To access the name of the related Parent object you would use:

cell.detailTextLabel.text = [[childMo valueForKey:@"parent"] valueForKey:@"name"];

Of course, if either the relationship or the parent.name attribute is optional, you should first check that either has a value before attempting to use the value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜