Friday, December 19, 2008

iPhone Application Development: Collections

Apple provides three basic collection classes: NSArray, NSSet, and NSDictionary. All three of these classes are non-mutable. i.e. once created, they cannot be changed. Their mutable equivalents are NSMutableArray, NSMutableSet, and NSMutableDictionary. All collections store objects only - primitive types can be wrapped in NSNumber and stored in collections.

NSArray is used to store lists of objects. An Ordered Collection. Primitive types can be wrapped in NSNumber. Common operations are supported: count, objectAtIndex, containsObject, etc. NSMutableArray contains additional operations: addObject, insertObject... atIndex, removeObject, removeObjectAtIndex, etc.

NSSet is a set of Objects. An Unordered Collection. An object might appear a maximum of one time. Operations supported are similar to NSArray.

NSDictionary: are equivalent to Map in Java. They store key, value pairs. Both keys and values are objects. Common supported operations: count, objectForKey, allKeys. NSMutableDictionary also supports editing operations such as setObject... forKey, removeObjectForKey.

NSDictionary supports saving to (writeToFile) and loading from (initWithContentsOfFile) files. These are usually called property lists or plists. The file created would be an XML file. Similarly, initWithContentsOfURL, writeToUrl are supported for URL operations.

Memory Management Reminder: Every collection retains an object when its added, and releases it when it is removed. Releasing a collection object releases all the objects stored in it as well.

No comments:

Post a Comment