An NSSet is nothing more than a collection of objects, called members. The NSSet class contain a number of methods specifically designed to ease the creation and manipulation of its members. An NSSet object stores its members (which can be any kind of object) under a given name. Objects instantiated (created) from the NSSet class are immutable. This means once you’ve instantiated and initialize a set, you can’t add new members or delete existing members from it. Here are three things you should never, never forget about objects instantiated from the NSSet class.
- Members of the set are not ordered.
- A member can only appear once in a set, no matter how many times it is added.
- Members of a set must be an Objective-C object, primitive C types, like int, float, etc. are not allowed.
The setWithObjects:, member: and allObjects Methods
The setWithObjects: method instantiates an immutable set object.
The memberr method determines if an object exist in the set, which you provide as it’s argument. The method returns that object if it exists in the set. By the way, the return data type of the member method is of type id. It is a general purpose data type that can be used to store a reference to any object, regardless of its type. Think of id as a wild card.
The allObjects method returns all members of a set as an unordered array. If the NSSet object has no members, the method will return an empty array.
Now, code below shows how to use all three methods.
Despite being added twice, @”white” only appears in the set once.
The Sort Members of an NSSet
Now, since the allObjects method returns members of colors set as an unordered array, you must use the sortedArrayUsingSelector: method to put elements of the array in alphabetical order, as shown below.
Common Immutable Set Methods
The NSSet class contain several methods for manipulating instances (objects) of the class. You learned how to use three of them above. In this section I show you how to use two more methods of the NSSet class.
The anyObject Method
This method display any member of a set, as demonstrated below.
Code | Output |
---|---|
self.outputBox.text = [colors anyObject]; |
The containsObject Method
This method returns a Boolean value (YES/NO) indicating whether a given object exists in a set. You can then use the value in an if statement as shown below.
The setWithArray: Method
This method turns an NSArray into an NSSet
. Since duplicate members are not allowed in a set, you can use the setWithArray method to remove duplicate elements that exist in an NSArray or NSMutableArray object.
Notice how the setWithArray: method on code line above, removed the duplicate element, The Passage from the novels array.