Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Collection
A collection is a Foundation framework object whose primary role is to store objects in the form of arrays, dictionaries, and sets.
Collection Classes
The primary classes—NSArray
, NSSet
, and NSDictionary
—share a number of features in common:
They can hold only objects, but the objects can be of any type. An instance of
NSArray
, for example, could contain cats, dogs, or wombats, or any combination of these.They maintain strong references to their contents.
They are immutable, but have a mutable subclass that allows you to change the contents of the collection.
You can iterate over their contents using
NSEnumerator
or fast enumeration.
Cocoa also provides three classes—NSPointerArray
, NSHashTable
, and NSMapTable
—that are modeled on these classes but that differ in the following ways:
They may contain elements other than objects.
They offer other memory management options.
They are mutable.
Since a Cocoa collection object can hold any sort of object (unlike collections in some other environments), you typically don’t create special collection classes to contain objects of a particular type.
Ordering Schemes
Collections store and vend other objects in a particular ordering scheme:
NSArray
and its mutable subclassNSMutableArray
use zero-based indexing.In other environments, an array may be called a vector, table, or list.
NSPointerArray
is modeled afterNSMutableArray
, but it can also holdNULL
values (which contribute to the object’s count). You can also set the count of the pointer array directly (something you can’t do in a traditional array).NSDictionary
and its mutable subclassNSMutableDictionary
use key-value pairs.In other environments, a dictionary may be referred to as a hash table or hash map.
NSMapTable
is modeled afterNSMutableDictionary
but provides different options, in particular to support weak relationships in a garbage-collected environment.NSSet
and its mutable subclassNSMutableSet
provide unordered storage of objects.Cocoa also provides
NSCountedSet
, which is a subclass ofNSMutableSet
and which keeps a count of how many times each object has been added to the set.NSHashTable
is modeled afterNSMutableSet
but provides different options, mostly to support weak relationships in a garbage-collected environment.
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-06