Chapter 24 — Collection Classes
The Collection Classes
- Can contain duplicates
- Will maintain the order of added objects
- No duplicate objects
- No guaranteed order
- Key/Value pairs
- Keys can’t be duplicates
- These collection objects can’t be changed once they are created.
- Higher performance. Should be used whenever possible.
- These collection objects can change. Objects can be added, moved, or deleted.
- Lower performance. Sometimes we have to use these.
- A Set can’t have duplicates. Here’s a quick demo. First, create a set and try to insert duplicates.
- Look at the results, no dups.
- A Dictionary holds a set of keys and values.
- There is a Modern Objective-C syntax for creating an NSDictionary.
- Here’s what they look like if you log one.
- To create an NSMutableDictionary we need to use a class method.
- Then we can manually add keys and values.
- Looking at our mutable dictionary.
- We access individual values with keys like this.
- Let’s look at an example of sorting and filtering arrays of objects from a class.
- Here’s the Student class we’ll use for the example.
- Let’s make a bunch of student objects.
- Then make an NSArray with them.
- Now we can sort and filter them.
- Pre-sorted output
- Let’s sort by last name and then first name. First we need a sort descriptor for each.
- Next, we need to make an array of the sort descriptors in the order of the sort.
- Now we perform the sort. Our original array is immutable so this code makes a copy.
- And the sorted result.
- Filtering to find a subset of the contents of an array.
- We start with an NSPredicate.
- Then create a new array by filtering.
- And here’s the output.
- The for in loop can be used with arrays, sets, and dictionaries.
- Here’s an example for an NSArray.
- It works just the same with sets.
- With an NSDictionary it’s a little different. It loops through the keys and you then access the values.
C primitive types
- Collections can only contain objects, not C primitives. What if you want to save ints or floats in a collection? We have to wrap them inside an object.
- We use the class NSNumber to hold any of the primitive C number types.
- Here’s the old way to make an array of ints and floats.
- And the display with NSLog.
- However, there’s a much easier way using Modern Objective-C.
- That’s it? Yup.