#import <Foundation/Foundation.h>
//使用Printing类别,将打印方法添加到NSSet
@interface NSSet (Printing)
- (void) print;
@end
@implementation NSSet (Printing)
- (void) print{
printf("{ ");
for(NSNumber *element in self)
printf(" %li", (long) [element integerValue]);
printf("} \n");//提醒我们如何通过创建分类将方法添加到类中
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableSet *set1 = [NSMutableSet setWithObjects: @1, @2, @5, @10, nil];
NSSet *set2 = [NSSet setWithObjects:@-5, @100, @3, @5, nil];
NSSet *set3 = [NSSet setWithObjects:@12, @200, @3, nil];//以一个nil结尾的对象数组创建新集合
NSLog(@"set1 = ");
[set1 print];
NSLog(@"set2: ");
[set2 print];
//相等性测试
if([set1 isEqualToSet: set2] == YES)//检测两个集合是否相等
NSLog(@"set1 equals set2");
else
NSLog(@"set1 is not equal to set2");
//成员测试
if([set1 containsObject: @10] == YES)//查询10是否在set1中
NSLog(@"set1 contains 10");
else
NSLog(@"set1 does not contain 10");
if([set2 containsObject: @10] == YES)
NSLog(@"set2 contains 10");
else
NSLog(@"set2 does not contain 10");
//在可变集合set1中添加移除对象
[set1 addObject: @4];
[set1 removeObject: @10];
NSLog(@"set1 after adding 4 and removing 10:");
[set1 print];
//获得两个集合的交集
[set1 intersectSet: set2];
NSLog(@"set1 intersect set2: ");
[set1 print];
//两个集合的并集
[set1 unionSet: set3];
NSLog(@"set1 union set3: ");
[set1 print];
//在这两种情况下,运算结果取代了消息的接收者(set1)改变
}
return 0;
}
Foundation框架同样提供了一个名为NSCountedSet的类。这种集合同一对象可以出现多次,然而并非在集合中存放多次这个对象,而是维护一个次数计数。当第一次将对象添加到集合时,对象的count值被置为1,然后每次将这个对象添加到集合中,count值就会增1,每次从集合删除对象,count值就会减1.当对象的count值为0时,实际上对象本身就被删除了。使用方法countForObject:可以在集合中检索某个对象count值。重要应用是单词计数器。