0

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have a data base which contains multiple rows. Each row contains section title column. Some rows have same section title value and some have different. To load this data into table view I need data based on sections. Any good suggestion how can I retrieve that data. I am using core data.
You're probably better off using an NSFetchedResultsController in that case.
Thank you Abizem. If I need to use NSCountedSet for custom objects in array. what would be the approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.