iosobjective-carraysnsmutablearraysup

Check if unique object exists in NSArray


I have an NSMutableArray where objects can be added to. The objects added are SUPDataValue objects containing a bunch of SUP data.

In an other view, I take this object array and divide it into an NSMutableArray containing an NSMutableArray for every section in the tableview. When add another SUPDataValue object to my initial Object array, and I switch back to my table view, I want to re-read all the object from the object array and see if those objects exist in my layered array.

I am using the "objectExists" and it works great... however... if I add the same object twice to my object array, it will always assume it exists in a layer.

This is my code:

- (void)setInitialComponents:(NSMutableArray*)components
{
    if (self.componentLayer)
    {
        for (SUPDataValueList *val in components)
        {
            BOOL found = NO;

            for (NSMutableArray *layer in self.componentLayer)
            {
                if ([layer containsObject:val])
                {
                    found = YES;
                }
            }

            if (!found)
            {
                [[self.componentLayer objectAtIndex:0] addObject:val];
            }
        }
    }
    else {
        self.componentLayer = [NSMutableArray array];

        // Add the no-layer layer (section 0)
        [self.componentLayer addObject:[NSMutableArray array]];

        if (self.addMode)
        {
            [[self.componentLayer objectAtIndex:0] addObjectsFromArray:components];
        }
        else {
            for (SUPDataValueList * val in components)
            {
                int layer = [[NSString stringWithFormat:@"%@", [val item:38]] intValue];

                if (self.componentLayer.count < layer)
                {
                    [self.componentLayer insertObject:[NSMutableArray array] atIndex:layer-1];
                }

                [[self.componentLayer objectAtIndex:layer-1] addObject:val];
            }
        }
    }

    [self.tableView reloadData];
}

As you might have guessed, my problem is here:

if ([layer containsObject:val])
{
    found = YES;
}

I would like to check if an unique object exist in that array (using memory allocation ID or something?) How do I do that?


Solution

  • The containsObject method will invoke isEqual: on the underlying objects being compared.

    Unless you implement isEqual: in the SUPDataValueList object, it will simply do a pointer comparison which is the default behavior of isEqual in NSObject.