Vladimir Despotovic Vladimir Despotovic - 1 year ago 98
Objective-C Question

In objective-C, how to traverse indexes (keys) and objects in NSMutableArray?

Is it possible to traverse NSMutableArray in the same way as associative array can be traversed, ie. getting the "id" and "item" in the each loop pass? I have a NSMutableArray, and I want to use it as an associative array, to traverse it and change it as one (as associative array). Is this possible to do, or do I have to use some more complex structure, like NSMutableDictionary - for this purpose?

Answer Source

If you want to use an NSMutableArray then you can use the following code to traverse the array while accessing both the index and the object:

NSMutableArray *someArray = ...;
for (NSUInteger index = 0; index < someArray.count; index++) {
    NSNumber *object = someArray[index]; // Assuming the array stores NSNumber*s

Another option would be using the enumeration block provided by the SDK:

NSMutableArray *someArray = ...;
[someArray enumerateObjectsUsingBlock:^(NSNumber* object, NSUInteger index, BOOL *stop) {

Please keep in mind that arrays have indices instead of custom keys. The index has to start from 0 and cannot have any gaps in between. If you want that behavior, then use an NSMutableDictionary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download