Check for duplicate objects in NSMutableArray?

I am adding objects (NSNumbers in this case) to NSMutableArray, and I wanted to check how best to check for duplicates in an array before adding. (I.e.)

Number to add
if (NSMutableArray does not contain Number) {
    add Number
}

EDIT:

Thank you so much, I was lucky in NSArray today, but I completely missed "containsObject". That would be very good, but looking at the NSMutableSet is a lot more than what I was looking for. One last question if I can:

while([mySet count] < 5) {
    NSNumber *numberToAdd = [NSNumber numberWithInt:random() %10];
    [mySet addObject:numberToAdd];
}

I don’t think it really matters, but is it better to check if the "containsObject" set is set or just throw away the duplicate and continue.

while([mySet count] < 5) {
    NSNumber *numberToAdd = [NSNumber numberWithInt:random() %10];
    if(!mySet containsObject:numberToAdd) [mySet addObject:numberToAdd];
}

Again much appreciated, it is really great and will save me a ton of time.

Gary

+3
source share
5

, NSMutableArray NSArray.

if (![theArray containsObject:theNumber]) {
  // does not contain.
}

( , NSMutableSet .)

+15

: , , . NSMutableSet , addObject:. ( ), , NSMutableSet .

, , , .

+5

, . , - , -containsObject:. , O(n*logn) , , , .

The general way to do this is, although in general for arbitrary data sets, the data should contain NSMutableSetnext to the array. Before adding to the array, check the set for the existence of the element. If it is already installed in the kit, do not add it. If not, add it to both.

Of course, if you don't care about order and only uniqueness, then don't use an array at all, just use Set.

+1
source

I have a category in NSMutableArray

@interface NSMutableArray (CategoryName)

- (void)addObjectUnique:(id)anObject;

@end

@implementation NSMutableArray (CategoryName)

- (void)addObjectUnique:(id)anObject
{
  if ([self containsObject:anObject]) {
    return;
  }
  [self addObject:anObject];
}

@end
+1
source

Try the following:

// Number to add is newNumber, myArray is your Mutable array
if(![myArray containsObject:newNumber])
{
  [myArray addObject:myNumber];
}
0
source

Source: https://habr.com/ru/post/1738982/


All Articles