set 一級單值對象的集合,並且它可以是可變的,也可以是不變的。操作包括:搜尋、添加、刪除集合中的成員(公用於可變以集合),比較兩個集合,計算兩個集合的交集和並集等。
下面是一個集合的代碼:
#import <Foundation/NSObject.h><br />#import <Foundation/NSSet.h><br />#import <Foundation/NSValue.h><br />#import <Foundation/NSArray.h><br />#import <Foundation/NSAutoreleasePool.h><br />#import <Foundation/NSString.h></p><p>//Create an integer object<br />#define INTOBJ(v) [NSNumber numberWithInteger: v]</p><p>//Add a print method to NSSet with the Pringing category</p><p>@interface NSSet(Printing)<br />-(void) print;<br />@end</p><p>@implementation NSSet(Printing)<br />-(void) print<br />{<br /> printf("{");</p><p> for (int i = 0; i < [[self allObjects] count]; i++)<br /> {<br /> printf("%Ii ",(long) [ [[self allObjects] objectAtIndex:i] integerValue]);<br /> }<br /> //for (NSNumber *element in self)<br /> //printf("%Ii", (long) [element integerValue]);</p><p> printf("}/n");<br />}<br />@end</p><p>int main(int argc, const char *argv[])<br />{<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];</p><p> NSMutableSet *set1 = [NSMutableSet setWithObjects:<br /> INTOBJ(1),INTOBJ(3),INTOBJ(5),INTOBJ(10),nil];</p><p> NSMutableSet *set2 = [NSMutableSet setWithObjects:<br /> INTOBJ(-5),INTOBJ(100),INTOBJ(3),INTOBJ(5),nil];</p><p> NSMutableSet *set3 = [NSMutableSet setWithObjects:<br /> INTOBJ(12),INTOBJ(200),INTOBJ(3),nil];</p><p> NSLog(@"set1:");<br /> [set1 print];<br /> NSLog(@"set2:");<br /> [set2 print];</p><p> //Equality test<br /> if([set1 isEqualToSet: set2] == YES)<br /> NSLog(@"set1 equals set2");<br /> else<br /> NSLog(@"set1 is not equal to set2");</p><p> //Membership test</p><p> if([set1 containsObject: INTOBJ(10)] == YES)<br /> NSLog(@"set1 contains 10");<br /> else<br /> NSLog(@"set1 does not contain 10");</p><p> if([set2 containsObject: INTOBJ(10)] == YES)<br /> NSLog(@"set2 contains 10");<br /> else<br /> NSLog(@"set2 does not contain 10");</p><p> //add and remove objects from mutable set set1<br /> [set1 addObject:INTOBJ(4)];<br /> [set1 removeObject:INTOBJ(10)];<br /> NSLog(@"set1 after adding 4 and removing 10:");<br /> [set1 print];</p><p> //get intersection of two sets<br /> [set1 intersectSet: set2];<br /> NSLog(@"set1 intersect set2:");<br /> [set1 print];</p><p> //union of two sets<br /> [set1 unionSet:set3];<br /> NSLog(@"set1 union set3:");<br /> [set1 print];</p><p> [pool drain];<br /> return 0;</p><p>}<br />