addObject not working with NSMutableSet

2.2k views Asked by At

I've tried to add an Object to the NSMutableSet but it doesn't work where it perfectly works fine with NSMutableArray.

//doesn't Work

[arr_NSMutableSet addObject:Object];
NSLog(@"%@",arr_NSMutableSet); // Shows nil

//Works fine
[arr_NSMutableArray addObject:Object];
NSLog(@"%@",arr_NSMutableArray); // Shows result

How to add the Object in NSMutableSet?

4

There are 4 answers

1
Aaron Brager On BEST ANSWER

arr_NSMutableSet is nil. You need to create it:

arr_NSMutableSet = [NSMutableSet set];
1
Alex Andrews On

Try like this, created a simple string object and added to the Mutable set like as folows

NSMutableSet *customSet = [NSMutableSet set];
NSString *str = @"str";
[customSet addObject:str];

Its working for me

1
Kai Schaller On

This usually happens to me because I forgot to initialize the set (or array, or dictionary...). Make sure you are doing the following:

NSMutableSet *mySet = [NSMutableSet set];

or, alternatively:

NSMutableSet *mySet = [[NSMutableSet alloc] init];
1
Nikita Khandelwal On
NSMutableSet *brokenCars = [NSMutableSet setWithObjects:
                            @"Honda Civic", @"Nissan Versa", nil];
NSMutableSet *repairedCars = [NSMutableSet setWithCapacity:5];
// "Fix" the Honda Civic
[brokenCars removeObject:@"Honda Civic"];
[repairedCars addObject:@"Honda Civic"];

You can try this