2

I have following NSCountedSet

<NSCountedSet: 0x53dfc0> (item1 [2000], item2 [9000], item3 [200], item4  [3000])

Now i want to remove item1 object from my set.
one solution is

while([mySet countForObject:item1])
 [mySet removeObject:item1];

Output:

<NSCountedSet: 0x53dfc0> (item2 [9000], item3 [200], item4  [3000])

or i want to remove only 1000 item1 object from my set.

    NSUInteger count = [mySet countForObject:item1];
    while(count)
    {
     [mySet removeObject:item1];
     --count;
    }

Output:

<NSCountedSet: 0x53dfc0> (item1 [1000], item2 [9000], item3 [200], item4  [3000])

is there any better solution for this ?

Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
  • if you know the object "item1", you can call directly "removeObject" without having the loop over mySet. – WhiteTiger May 28 '12 at 13:13
  • @WhiteTiger [removeObject:](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSCountedSet_Class/Reference/Reference.html) decrements the count associated with NSCountedSet. – Parag Bafna May 28 '12 at 13:16

3 Answers3

2

You could filter with a predicate

[mySet filterUsingPredicate:[NSPredicate predicateWithFormat:@"self != %@", item1]];
Paul.s
  • 38,494
  • 5
  • 70
  • 88
0

I do not think you understand the problem, so I get these results:

<NSCountedSet: 0x6d9ee40> (two [1], three [1], one [1], four [1])

[mySet removeObject:@"one"];

<NSCountedSet: 0x6d9ee40> (two [1], three [1], four [1])
WhiteTiger
  • 1,691
  • 1
  • 18
  • 23
  • Stick `[mySet addObject:@"one"];` before your `removeObject:` to see this does not work... – Paul.s May 28 '12 at 13:37
  • @WhiteTiger your set contain only one [1](count is 1), i have item1 [2000] (count is 2000). – Parag Bafna May 28 '12 at 13:43
  • i hadn't realized you could have the possibility of having duplicate items – WhiteTiger May 28 '12 at 13:46
  • 1
    @WhiteTiger: Such is the purpose of a counted set: it tells you how many of each item is in it. Other kinds of sets do not allow duplicates; every item is either in a non-counted set or not. – Peter Hosey May 28 '12 at 23:53
0

NSCountedSet does not offer methods to modify the count of a certain object by a certain amount (a pity really).

If speed is not an issue you can used the methods you described above. However if you need something else: subclassing NSMutableSet to provide this "counting" functionality is probably your best option.

diegoreymendez
  • 1,997
  • 18
  • 20