I have an array which contains objects some may be same and some are different.
How can I take each same objects and different objects separately ?
Below is the array
NSMutableArray *items = [[NSMutableArray alloc]
initWithArray:[NSArray arrayWithObjects:@"rat", @"rat", @"cat",@"Lion", @"cat", @"dog", @"dog", nil]];
I want to have four arrays which will contains these items :
- First array with two rats
- 2nd array with two cats
- 3rd array with one lion
- 4th array with two dogs
What could be the best way to take the objects out ? Identical object should be placed in same array.
Here’s a general answer:
Put the array into an NSCountedSet – that will store each object and a count of the number of times it has been added.
Then – for each object in this counted set create an array with that object repeated according to the count of each object.
It will work in your case, because you are using static strings, which are going to be the same if they are the same string. This will take more work if you are using custom objects.
But the real question we have to ask is why you need to create these repetitive structures. If we could know what you are doing with it, we could give you better advice about how to go about it. For example, if you just need to keep a running count of the number of each type of object you have, you could just use the NSCountedSet directly (it descends from NSMutableSet, so it is already mutable) and not bother with creating the arrays.