Multidimensional Arrays

im trying to populate UITable XML, I already checked the xml and saved it in an array

ex.

array [item0, item1, item2, item3, item4, item5, item6, item7]

I need help trying to convert an array to an array with 2 columns

ex

array [[item0, item1], [item2, item3], [item4, item5], [item6, item7]]

any help would be greatly appreciated thanks

+1
source share
2 answers

You can use something like this.

NSMutableArray *rootArray = [NSMutableArray array];
for (NSInteger i = 1; i < [items count]; i+=2) {
    id object1 = [items objectAtIndex:i-1];
    id object2 = [items objectAtIndex:i];
    [rootArray addObject:[NSArray arrayWithObjects:object1, object2, nil]];
}

This will ignore the last object if you have an odd number of objects in your array.


Change, a version that does not ignore the last single object.

NSMutableArray *rootArray = [NSMutableArray array];
for (NSInteger i = 0; i < [items count]; i += 2) {
    id object1 = [items objectAtIndex:i];
    id object2 = nil;
    if (i+1 < [items count]) {
        object2 = [items objectAtIndex:i+1];
    }
    [rootArray addObject:[NSArray arrayWithObjects:object1, object2, nil]];
}
+2
source

create a structure like

    NSMutableArray *dictArray=[NSMutableArray alloc] init];
            for(int i=0;i<[array count];i=i+2)
            {
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
                [dict setObject:[array objectAtIndex:i] forKey:@"first"];
                if([array count]>(i+1))
                  [dict setObject:[array objectAtIndex:(i+1)] forKey:@"second"];
                    [dictArray addObject:dict];
[dict release];
            }

      [dictArray release];
0
source

All Articles