NSSet和 NSMutableSet
#import <Foundation/Foundation.h>
@interface NSSet (Printing)
-(void)print ;
@end
@implementation NSSet (Printing)
-(void) print {
printf("{") ;
for ( NSNumber *element in self ) {
printf(" %li ", (long)[element integerValue] ) ;
}
printf("}") ;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableSet *set1 = [NSMutableSet setWithObjects:@1,@3,@5,@10, nil] ;
NSSet *set2 = [NSSet setWithObjects:@-5,@100,@3,@5, nil] ;
NSSet *set3 = [NSSet setWithObjects:@12,@200,@3, nil] ;
NSLog(@"set1 :") ;
[set1 print] ;
NSLog(@"set2 :") ;
[set2 print] ;
//相等性测试
if ( [set1 containsObject: @10 ] == YES ) {
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 和set2 是否相等
BOOL a = [set2 isEqual:set1];
if ( a == YES ) {
NSLog(@"两个集合相等");
} else {
NSLog(@"两个集合不相等") ;
}
//确定接收者中每个成员都是否出现在对象中
BOOL b = [set2 isSubsetOfSet:set1] ;
if ( b == YES ) {
NSLog(@"set2 中的成员都出现在set1 中");
} else {
NSLog(@"set2 中的成员不都出现在set1 中");
}
//确定接收者中是否至少有一个成员出现在对象中
//是否为子集合
BOOL c = [set2 intersectsSet:set1] ;
if ( c == YES ) {
NSLog(@"set2 中有成员出现在set1 中") ;
} else {
NSLog(@"set2 中没有成员出现在set1 中") ;
}
//集合成员的个数
NSInteger count = [set2 count] ;
NSLog(@"count = %li",count) ;
//在可变集合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:set2] ;
NSLog(@"set1 union set2 :") ;
[set1 print] ;
//数组转集合
NSArray *array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil ] ;
NSSet *set = [[NSSet alloc] initWithArray:array] ;
NSLog(@"set:%@",set) ;
//集合转数组
NSArray *array2 = [set allObjects] ;
NSLog(@"%@",array2);
}
return 0;