Objective-C學習筆記-NSSet與NSDictionary
阿新 • • 發佈:2018-12-11
1.NSSet與NSArray的區別就是NSSet裡面的值是不可重複且無序的,在查詢速度上NSSet比NSArray更快,而NSDictionary則可以儲存鍵值對,這個鍵值對也是無序的,鍵通常是一個字串(唯一的),而值可以是任意型別的物件
2.和NSArray一樣,NSSet和NSDictionary也是不可修改的,要想增加刪除,可以使用NSMutableSet,NSMutableDictionary
3.NSSet初始化
NSSet *assets1=[NSSet setWithObjects:@"abc",@"def",nil]; NSSet *assets2=[[NSSet alloc] initWithObjects:@"1",@111,@222,nil]; NSLog(@"assets1 count=%ld",[assets1 count]); NSLog(@"assets2 count=%ld",[assets2 count]);
4.NSSet遍歷
NSEnumerator *enumer=[assets2 objectEnumerator];
id object;
while ((object=[enumer nextObject])!=nil){
NSLog(@"%@",object);
}
5.NSSet查詢
if ([assets containsObject:@"111"]){
NSLog(@"yes");
}
5.NSMutableSet增加與刪除
NSMutableSet * assets = [[NSMutableSet alloc] init]; [assets addObject:@"111"]; [assets addObject:@"222"]; [assets addObject:@"333"]; [assets removeObject:@"333"]; [assets removeAllObjects];
6.NSDictionary初始化
NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1", nil];
NSDictionary *[email protected]{@"key1":@111,@"key2":@222};
NSLog(@"%@",dic1[@"key1"]);
NSLog(@"%ld",dic2.count);
7.NSDictionary遍歷
NSArray* keys=[dic2 allKeys]; for (int i=0;i<keys.count;i++){ NSLog(@"%@",[dic2 objectForKey:keys[i]]); } NSEnumerator *enumer=[dic2 objectEnumerator]; id object; while ((object=[enumer nextObject])!=nil){ NSLog(@"%@",object); }
8.NSDictionary初始化,增加,刪除
NSMutableDictionary *dic2=[[NSMutableDictionary alloc] initWithCapacity:0];
[dic2 setObject:@333 forKey:@"key3"];
[dic2 setObject:@111 forKey:@"key1"];
[dic2 removeObjectForKey:@"key3"];
[dic2 removeAllObjects];