Objective-C学习笔记-NSSet与NSDictionary

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 *dic2=@{@"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];

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页