Objective-Cの集合(NSSetとNSMutableSet)基本概念とよく利用方法

1.初期化
NSSet *set1=[[NSSet alloc]initWithObjects:@"one",@"tow", nil];
NSLog(@"%@",set1);

2.不変な集合—NSSet

2.1 配列を利用
NSArray *array1=[NSArray arrayWithObjects:@"one",@"tow", nil];
NSSet *set2=[NSSet setWithArray:array1];
NSLog(@"%@",set2);

2.2 既存の集合を利用して作り上げ
NSSet *set3=[NSSet setWithSet:set2];
NSLog(@"%@",set3);

2.3 集合オブジェクトの数量
NSInteger *count=[set3 count];
NSLog(@"%ld",count);

2.4 集合のすべての要素に戻る
NSArray *array2 =[set3 allObjects];
NSLog(@"%@",array2);

2.5 集合の任意の要素に戻る
NSString *str=[set3 anyObject];
NSLog(@"%@",str);

2.6 集合の中にある要素が存在するかどうか
Boolean result1=[set3 containsObject:@"two"];
if(result1){
NSLog(@"twoが含む"); }
else{ NSLog(@"twoが含まれない"); }

 

2.7 集合と集合の間にこもごも至りがあるかどうかを検索
BOOL result2= [set1 intersectsSet:set2];
NSLog(@"%d",result2);

2.8 集合をマッチング
BOOL result3=[set1 isEqualToSet:set2];
NSLog(@"%d",result3);

2.9 集合のサブセットであるかどうか
BOOL result4=[set1 isSubsetOfSet:set2];
NSLog(@"%d",result4);

2.10 一つの集合に一つの要素を追加して、新しい集合に戻る
NSSet *set5=[NSSet setWithObjects:@"one",nil];
NSSet *appSet=[set5 setByAddingObject:@"tow"];
NSLog(@"%@",appSet);
2.11:一つの集合にもう一個集合を追加して、新しい集合に戻る
NSSet *set6=[NSSet setWithObjects:@"1″,@"2″, nil];
NSSet *appSet1=[set5 setByAddingObjectsFromSet:set6];
NSLog(@"%@",appSet1);

2.12 一つの集合に配列を追加して、新しい集合を戻す
NSArray *appArray=[NSArray arrayWithObjects:@"x",@"y", nil];
NSSet *appSet2=[set5 setByAddingObjectsFromArray:appArray];
NSLog(@"%@",appSet2);
3.可変集合—NSMutableSet

3.1 初期化の可変集合を作成
NSMutableSet *mutableSet1=[NSMutableSet Set];//空集合
NSMutableSet *mutableSet2=[NSMutableSet setWithObjects:@"1″,@"2″, nil];
NSMutableSet *mutableSet3=[NSMutableSet setWithObjects:@"a",@"2″, nil];
3.2 集合から同じ要素を除去する
[mutableSet2 minusSet:mutableSet3];
NSLog(@"%@",mutableSet2);

3.3 2つの集合の公共の要素を求める
[mutableSet2 intersectSet:mutableSet3];
NSLog(@"%@",mutableSet2);

3.4 2つの集合をマージする
[mutableSet2 unionSet:mutableSet3];
NSLog(@"%@",mutableSet2);

 

IOS

Posted by arkgame