Search code examples
objective-carraysnsarraynsdictionary

Iterating through Obj-C Arrays


How do you navigate through arrays in Objective-C? Take the following example.

    (
        [key] => value
        [key] => value
    )

Any advice out there?

6 years later I realize how moronic this question is. I'm sorry Stack Overflow.


Solution

  • "Navigate" is a rather ambiguous term, as it could mean "loop" or "index". "Iterate" is a synonym for "loop". Sometimes people use "dereference" for "index", but dereferencing is properly applied only to pointers when accessing what is pointed to. In some languages, such as C, indexing involves dereferencing (which is why dereference is used in this way), but this isn't true in general, and isn't true of NSArrays in Objective-C.

    Arrays in Objective-C, as in most other languages, are only integer indexed. Dictionaries are the data structures that are indexed by strings; in Objective-C, dictionaries are available as NSDictionary and NSMutableDictionary. Dictionaries are also known as "associative arrays", which often gets shortened to "arrays" when talking about PHP, since all arrays in PHP are associative.

    You index a dictionary with the objectForKey: method:

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithDouble:120.50],@"balance",
        @"myuser",@"username"
        nil];
    
    NSLog(@"%@", [dict objectForKey:@"balance"]);
    NSLog(@"%@", [dict objectForKey:@"username"]);
    

    You can add an item to an NSMutableDictionary using setObject:forKey::

    // mutableDict is an owning reference; if not using ARC, it must be released
    NSMutableDictionary *mutableDict = [dict mutableCopyWithZone:NULL];
    [mutableDict setObject:@"bar" forKey:@"foo"];
    

    You can loop over keys with fast enumeration syntax:

    for (id key in dict) {
        NSLog(@"%@: %@", key, [dict objectForKey:key]);
    }
    

    Both iteration and indexing are the most basic array operations. If your current source for Objective-C information doesn't discuss them, find a new source. If you don't have a source, find one. You'll never learn all that you need without one.

    See also: