三種集合類
NSSArray 用于對象有序集合(NSObject對象)
NSSet 用于對象的無序集合
NSDictionary 永固鍵值映射
以上三種集合類是不可變的(一旦初始化, 就不能改變)
以下是對應的三種可變集合類(者三種可變集合類是對應上面三種集合類的子類)
NSMutableArray
NSMutableSet
NSMutableDictionary
1. 字典的定義
字典用于保存具有映射關系(Key - value對)數據的集合,
對于 "name : 張三" 來講, key就是"name" , key對應的value值就是"張三", 一個key-value對認為是一個條(Entry), 字典是存儲key-value對的容器!
- 字典的特點
- 與數組不同, 字典靠key存取元素;
- key值不能重復; value必須是對象;
- 鍵值對在字典中是無序存儲的
- NSDictionary 不可變字典
- 創建字典
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
@"male", @"sex",
@"20", @"age",
@"Tom", @"name",
@"run",@"hobby", nil ];` - 獲取所有的key值和所有的Value值
[dic allKeys];
[dic allValues];
- 根據key值獲取Value值
[dic valueForkey:@"name"];
NSLog(@"%@", [dic valueForKey:@"name"])
- 遍歷字典
for-in 循環 快速遍歷, 根據存在的對象類型輸出
for (NSString *key in dic) {
NSLog(@"%@", key) // key為NSString可I型, 所以能遍歷一邊!
}
- 創建字典
- NSMutableDictionary
- 初始化字典
NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
@"male", @"sex",
@"20", @"age",
@"tom", @"name",
@"run", @"hobby"]; - 向字典中添加字典: //
NSDictionary *dict4=[NSDictionary dictionaryWithObject:@"v6"forKey:@"k6"];
- 初始化字典
[mutableDic addEntriesFromDictionary:dict4];
表示 把dict4字典中的對象和key值添加到了mutableDic中
向字典中添加value 和 key
[mutableDic setValue:@"object" forKey:@"key"];
創建空的字典 , 并設置新的一個字典
NSMutableDictionary *mutableDict2 = [NSMutableDictionary dictionary];
`[mutableDict2 setDictionary:mutableDic];刪除指定key的value值
[mutableDict2 removeObjectForKey:@"k4"];
刪除移除key集合的value值
NSArray *arrayKeys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3",nil];
[mutableDict2 removeObjectsForKeys:arrayKeys];刪除字典中的所有value值
[mutableDict2 removeAllObjects];
// 刪除所有value值
2.集合
不可變集合:
Foundation框架中, 提供了NSSet類, 它是一組單值對象的集合, 且NSSet實例中元素是無序的, 用一個對象只能保存一個, 并且它也分為可變和不可變
創建集合
NSSet *set1 = [[NSSet alloc] initWithObjects:@"one", @"two", nil];
通過數組構建集合
NSArray *array = [NSArray aarayWithObjects:@"one", @"two", nil];
NSSet *set = [NSSet setWithArray: array1];
通過已有集合構建集合
NSSet *set3 = [NSSet setWithSet : set2];
集合對象數量
NSInteger *count = [set3 count]; NSLog(@"%ld", count);
返回集合中任意元素
NSString *str = [set3 anyObject];
// 注意返回的集合中的任意值, 隨機出現給集合中添加新元素
NSSet *set1 = [NSSet setWithObject: @"one", nil];
NSSet *appSet = [set1 setByAddingObject:@"two"]; NSLog(@"%@", appSet);
可變集合
初始化
NSMutableSet *mutableSet1 =[NSMutableSet Set];
NSMutableSet *mutableSet2 = [NSMutableSet setWithObjects:@"1", @"2", nil];
從集合中去除相同的元素
[mutableSet1 minusSet: mutableSet2];
從mutableSet2去除mutableSet3中相同的!得到兩個集合的公共元素
[mutableSet1 intersectSet:mutableSet2];
mSet1 只留下與mSet2相同的元素合并兩個集合的元素
[mutableSet unionSet: mutableSet3];