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

前端 未结 3 1737
再見小時候
再見小時候 2021-01-27 05:48

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?

3条回答
  •  离开以前
    2021-01-27 06:38

    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]];
    

提交回复
热议问题