Search code examples
iosobjective-cnsmutablearraynsarraynsset

Can I addobject to nsmutablearray only if addobject to nsset is successful?


I only want to add unique objects to a set hence the reason I am using an NSSet. If an object is successfully added to that set I want to add an object to an array. Is there any way to do this? Can I make NSSet return something when an object is successfully added to it?


Solution

  • You could compare the count of the NSSet before and after attempting the add.

    NSInteger setCount = [mySet count];
    [mySet addObject:foo];
    if ([mySet count] > setCount) {
        // object was added
    }
    

    You could also perform a containsObject test before adding the object:

    if ([mySet containsObject:foo]) {
        // object already exists
    } else {
        // object is not yet in the set
        [mySet addObject:foo];
        [myArray addObject:foo];
    }
    

    Yet another option is to simply add objects to a set, then convert the set to an array when you are done:

    [mySet addObject:foo];
    NSArray *myArray = [mySet allObjects];