Sorry for the simple question, but I am self taught and know that there are gaps in my education.
To print an array in objective C, I believe is:
NSLog(@"My array: %@", myArray);
How can I print an array of arrays?
Thanks
You want this:
for(NSArray *subArray in myArray) {
    NSLog(@"Array in myArray: %@",subArray);
}
This will work for an array that has arrays nested one level deep.
You don't need to do anything different to log an array of arrays; the code exactly as you've written it will already show the contents of the sub-arrays.
That is, the following program:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray *array = [NSMutableArray array];
    for (int i=0; i<5; ++i) {
        NSMutableArray *sub = [NSMutableArray array];
        for (int j=0; j<=i; ++j) {
            [sub addObject:[NSString stringWithFormat:@"%d", j]];
        }
        [array addObject:sub];
    }
    NSLog(@"Array: %@", array);
    [pool drain];
    return 0;
}
Produces the following output:
Array: (
        (
        0
    ),
        (
        0,
        1
    ),
        (
        0,
        1,
        2
    ),
        (
        0,
        1,
        2,
        3
    ),
        (
        0,
        1,
        2,
        3,
        4
    )
)
Clearly, it's already logging the sub-arrays just fine. If you want to control the formatting differently, you'd have to manually iterate them, but by default, the -description of an NSArray is little more than the -description of every object in that array, which includes all sub-arrays.
So I was embarrassed by the recursiveDescription thing, so I wrote my own as a category on NSArray. Note that this code will print out a description for an array of arrays to any depth. The description itself could probably use a bit more formatting than commas and newlines. Here you go:
@interface NSArray (RecursiveDescription)
- (NSString *)recursiveDescription;
@end
@implementation NSArray (RecursiveDescription)
- (NSString *)recursiveDescription {
    NSMutableString *description = [[NSMutableString alloc] initWithString:@"Array (\n"];
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    for (NSObject *child in self) {
        if ([child respondsToSelector:@selector(recursiveDescription)]) {
            [description appendFormat:@"%@,\n", [child recursiveDescription]];
        }
        else {
            [description appendFormat:@"%@,\n", [child description]];
        }
    }
    [pool drain];
    [description appendString:@"\n)"];
    return [description autorelease];
}
@end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With