How do I put objects in an NSArray into an NSSet?
This is not correct:
NSSet *telephoneSet = [[NSSet alloc] init];
[telephoneSet setByAddingObjectsFromArray:telephoneArray];
That method returns an NSSet which you are doing nothing with (it doesn't add the objects to telephoneSet, it creates a new NSSet). Do this instead:
NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]
Also, note that a set cannot contain duplicates unlike an array. So if you have duplicate objects in your array and you put them in a set, the duplicates will be removed which can affect the object count.
Initially telephoneArray
contains references to n
distinct objects. After the loop ends, it does contain n
references, but each one is pointing to the same newTelephone
object.
Array can contain duplicates, so it doesn't matter. A Set cannot have duplicates, and your entire telephoneArray is composed of a single object basically, so you're seeing just one.
In your loop, you have to create a new object or get a telephone object from somewhere:
for (int i=0; i<[telephoneArray count]; i++) {
// Create the new object first, or get it from somewhere.
Telephone *newTelephone = [[Telephone alloc] init];
[newTelephone setBranch:newBranch];
[newTelephone setNumber:[[telephoneArray objectAtIndex:i] valueForKey:@"number"]];
[telephoneArray replaceObjectAtIndex:i withObject:newTelephone];
// the array holds a reference, so you could let go of newTelephone
[newTelephone release];
}
Also, like PCWiz said, you don't need to allocate a new NSSet
object in your case. Just call the class method setWithArray:
.
NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]
Swift 3 Version
You can create a new NSSet from an array with:
let mySet = NSSet(array : myArray)
Additionally, you can add objects from an array to an already existing NSMutableSet with.
myMutableSet = myMutableSet.addingObjects(from: myArray)