Search code examples
objective-cios7nsarraynsset

Using addObjectsFromArray on a nil NSMutableSet


I have an array (arrayA) of type NSArray having custom objects in it and a NSMutableSet (setA) also having the custom objects of same class. I wish to merge the contents in both of these in a set to avoid duplicate values, so I used [setA addObjectsFromArray:arrayA] and then I print setA.

I have a scenario where in setA would be nil and arrayA would have some contents in it. My understanding was even if setA is nil, [setA addObjectsFromArray:arrayA] would add contents of arrayA in SetA, but when I print setA I get nil instead of objects in setA.

How does this "addObjectsFromArray" work exactly? or am I missing something here? Apple docs didn't give me much idea about the nil part of the set.


Solution

  • If an object is nil and you call a method on it, it will also return nil. Add a check of setA is nil, set it to a new NSMutableSet.

    Remember, [nil method] always performs a noop. If you id retVal = [nil methodThatReturnsObjParam], retVal will always be nil. If you int iVal = [nil methodThatReturnsint], iVal will be 0. And so on.