Frage

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?

War es hilfreich?

Lösung

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];

Andere Tipps

Use [set count] before and after the insert to see if anything was added.

int prior = [set count];
[set addObject:obj];
if (prior < [set count]) {
  [array addObject:obj];
}

I am not sure why would you want to do that as long as you are adding the same object both in your array and set. Simply add all the objects to your NSSet and then call the below method on it to get NSMutableArray.

NSMutableArray *uniqueItems = [NSMutableArray arrayWithArray:[mySet allObjects]];

You might consider using NSMutableOrderedSet that will allow you to maintain only 1 collection instead of 2.

addObject:
Appends a given object to the mutable ordered set, if it is not already a member.

NOTE: This class is iOS 5 and above.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top