How to get at a relationship items properties in Core Data?

早过忘川 提交于 2019-12-20 05:46:09

问题


Say you have a Core Data object called Workshop. It has a to-many relationship to a Student object.

How would I create an NSArray of the students within the Workshop?


回答1:


It's a NSSet opposed to an array, as they are unordered.

Use mutableSetValueForKey: This returns a proxy that mutates the relationship and does KVO notifications. Think of the name as "[NS]MutableSet" "valueForKey" rather than "mutableSetValue" "forKey", because it returns a mutable set that you manipulate

NSMutableSet *Students;
Students = [Workshop mutableSetValueForKey: @"Students"];
[Students addObject: newStudent];
[Students removeObject: oldStudent];

source




回答2:


These relationships are normally declared as an NSSet in your NSManagedObject subclass, like this:

@property (retain) NSSet* students;

And there's also some special accessor methods:

- (void)addStudentsObject:(NSManagedObject *)value;
- (void)removeStudentsObject:(NSManagedObject *)value;
- (void)addStudents:(NSSet *)value;
- (void)removeStudents:(NSSet *)value;

NSSets are similar to NSArrays, but they are not ordered, since Core Data does not guarantee a special sort order for managed objects.




回答3:


You usually have no need to create an array of a to-many relationship because they automatically come in a NSSet anyway. This gives better flexibility than an array.

However, if you need students sorted in a particular order you can use a sort descriptor to return a sorted array. Suppose you already have the WorkShop instances and you wanted an array of students sorted by last name in descending order, you would use this:

WorkShop *aWorkShop=//... fetch the appropiate WorkShop instances
NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:NO];
NSArray *sortedStudents=[aWorkShop.students sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];


来源:https://stackoverflow.com/questions/4206788/how-to-get-at-a-relationship-items-properties-in-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!