2010-11-17 132 views

回答

1

这是一个与数组相反的NSSet,因为它们是无序的。

使用mutableSetValueForKey:这 返回变异的 关系,也不KVO 通知代理。名字看作 “[NS] MutableSet” “valueForKey”,而 不是 “mutableSetValue” “forKey”, 因为它返回一个可变的集合 您操作

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

source

2

这些关系通常被声明为您的NSManagedObject子类的NSSet,像这样:

@property (retain) NSSet* students; 

还有还有一些特殊的存取方法:

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

NSSets类似于NSArrays,但他们没有排序,因为核心数据不能保证管理对象的特殊排序顺序。

1

您通常不需要创建一个多对多关系的数组,因为他们无论如何都会自动进入NSSet。这比数组提供了更好的灵活性。

但是,如果您需要按特定顺序排序的学生,则可以使用排序描述符来返回排序后的数组。假设你已经有了WorkShop实例,并且你想要一个按姓氏排序的学生排列顺序,你可以这样使用:

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