Objective-C learning notes - NSSet and NSDictionary

1. The difference between NSSet and NSArray is that the values in NSSet are unrepeatable and unordered. In terms of search speed, NSSet is faster than NSArray, while NSDictionary can store key value pairs, which are unordered. The key is usually a string (unique), and the value can be any type of object

2. Like NSArray, NSSet and NSDictionary are immutable. To add or delete them, you can use NSMutableSet and NSMutableDictionary

3.NSSet initialization

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 traversal

NSEnumerator *enumer=[assets2 objectEnumerator];
id object;
while ((object=[enumer nextObject])!=nil){
    NSLog(@"%@",object);
}

5.NSSet lookup

if ([assets containsObject:@"111"]){
    NSLog(@"yes");
}

5.NSMutableSet addition and deletion

NSMutableSet * assets = [[NSMutableSet alloc] init];
[assets addObject:@"111"];
[assets addObject:@"222"];
[assets addObject:@"333"];
[assets removeObject:@"333"];
[assets removeAllObjects];

6.NSDictionary initialization

NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1", nil];
NSDictionary *dic2=@{@"key1":@111,@"key2":@222};
NSLog(@"%@",dic1[@"key1"]);
NSLog(@"%ld",dic2.count);

7.NSDictionary traversal

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 addition and deletion

NSMutableDictionary *dic2=[[NSMutableDictionary alloc] initWithCapacity:0];
[dic2 setObject:@333 forKey:@"key3"];
[dic2 setObject:@111 forKey:@"key1"];
[dic2 removeObjectForKey:@"key3"];
[dic2 removeAllObjects];

 

Posted by threaders on Thu, 26 Dec 2019 12:40:48 -0800