iOS set types - NSSet and NSMutableSet

Collection has the characteristics of unique and unordered data.

NSSet is an immutable set. It is like NSString when it can be initialized. You can inherit the data of NSObject type to NSString. For example, the basic types int and bool are not allowed. They need to be converted to NSNumber

The NSSet operation is as follows

  NSSet *set1 = [NSSet setWithObjects:@"one",@"two",@"two",@"three",@"three",@"four",@"five",nil];
    NSSet *set2 = [NSSet setWithObjects:@"two",@"three",nil];
    
    NSLog(@"set1 count:%lu", [set1 count]);

    //Determine whether there is one string
    if([set1 containsObject:@"one"]) {
        NSLog(@"set1 Contain one");
    }
    //Determine whether set is equal to set1
    if ([set1 isEqualToSet:set2]) {
        NSLog(@"set1 Be equal to set2");
    }
    //Determine whether set is a subset of set1
    if ([set1 isSubsetOfSet:set2]) {
        NSLog(@"set1 Contains set2");
    }
    //Get all set objects and convert to NSArray
    NSArray *array = [set1 allObjects];
    NSLog(@"array:%@", array);
    
    //Iterative traversal
    NSEnumerator *enumerator = [set1 objectEnumerator];
    for (NSObject *object in enumerator) {
        NSLog(@"set1 Objects in:%@", object);
    }
Then there is the use method of NSMutableSet. Although it inherits the NSSet and can use all the public functions of NSSet, its use of isEqualToSet and isSubsetOfSet is useless for NSMutableSet, and it returns false. If it is the NSSet function, it can get the correct result

 NSMutableSet * muSet1 = [[NSMutableSet alloc]init];
    [muSet1 addObject:@"one"];
    NSSet *set3 = [NSSet setWithObjects:@"one",@"two",@"two",@"three",@"three",@"four",@"five",nil];
    //Add set data
    [muSet1 unionSet:set3];
    for (NSObject *object in muSet1) {
        NSLog(@"muSet1:%@",object);
    }
    NSLog(@"--------------------");
    NSSet *set4 = [NSSet setWithObjects:@"two",@"three",@"six", nil];
    
    //Delete the total data containing set1 in muSet
    [muSet1 minusSet:set4];
    for (NSObject *object in muSet1) {
        NSLog(@"muSet1:%@",object);
    }
    NSLog(@"--------------------");
    NSMutableSet * muSet2 = [[NSMutableSet alloc]init];
    [muSet2 addObject:@"one"];
    
    if([muSet1 containsObject:@"one"]){
        NSLog(@"muSet1 Contains one");
    }
   
    if([muSet1 isEqualToSet:muSet2]){
        NSLog(@"muSet1 Be equal to muSet2");
    }
    
    if([muSet1 isSubsetOfSet: muSet2]){
        NSLog(@"muSet1 Contains muSet2");
    }







Posted by Richard on Sat, 02 May 2020 22:36:42 -0700