1

im trying to populate a UITable with XML, i already have the xml parsed and stored in an array

ex.

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

i need help trying to convert the array into an array that has 2 columns

ex

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

any help would be greatly appreciated thanks

Matthew Frederick
  • 22,245
  • 10
  • 71
  • 97
user616860
  • 309
  • 1
  • 3
  • 10

2 Answers2

2

You could 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 a uneven number of objects in your array.


Edit, the version that doesn't 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]];
}
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
0

make structure some thing like this

    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];
Ishu
  • 12,797
  • 5
  • 35
  • 51
  • this will give him a dictionary with only "item6" and "item7". Not exactly what he wanted. – Matthias Bauch Feb 17 '11 at 07:12
  • this will create an array that has the same (as in: has the same values too) dictionary in all fields. You have another try ;) – Matthias Bauch Feb 17 '11 at 07:20
  • But he can use this same as multidimensional array.where he want to access data fro second column pick dictionary wtih "second" key and do what he want. – Ishu Feb 17 '11 at 07:23
  • try your code. You will see what is wrong. Hint: you should move the creation of the dictionary (and the release of course) inside the for loop. – Matthias Bauch Feb 17 '11 at 07:27
  • @fluchtpunkt,humm now i move creation and release inside loop,i think when i make it outside and release also it replace all objects with same.At the time when i gave the answer i just right code with my logic mot try that.at this time i also did not try but i think problem arises. any ways thanx. – Ishu Feb 17 '11 at 07:39