2010-11-17 128 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]];