I’m currently in the development process of an application which needs to be able to grab two objects from an NSArray and then store it in another object.
I’ve currently got this fast enumeration loop going on,
NSUInteger count = 0;
NSUInteger i = count + 1;
for (id item in [section items]) {
item1 = [section.items objectAtIndex:count];
item2 = [section.items objectAtIndex:i];
count++;
}
Now, what I want to do is grab the object in the first position and store in item1, and then the second position will be stored in item2. The next time it goes through the loop, I want it to store the object in the third position in item1, and then the fourth position in item2 and so forth.
Has anyone ever tried to and achieved this?
EDIT
This is what I currently have, I thought it best that I explain what I’m doing a little deeper so here goes. Here’s the code that I have first, and I’ll explain afterwards.
MPSection *section = [self.sections objectAtIndex:indexPath.section];
NSArray *itemArray = [section items];
for (NSUInteger i = 0; (i + 1) < [section.items count]; i += 2) {
item1 = [itemArray objectAtIndex:i];
item2 = [itemArray objectAtIndex:i+1];
}
As you can see, this is running within (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath as I want to grab what would normally be displayed in the first and second row of a UITableView and put it into one cell which is divided into two subviews.
What I’m finding is, by using the above code, it definitely isn’t doing that. Is there a simpler way that I can do this and if so, can someone please inform me about this. I really need to approach this with memory preservation and time consumption kept to a minimal as well.
It would be good if you can preprocess this but if you can’t do that for some reason then this is what you should do,
And in
tableView:cellForRowAtIndexPath:method,Original Answer
Use the
NSEnumeratorinstance for this purposeAs such I think you must be getting index out of bounds error for the snippet you mentioned.
Overkill
There seems to be some question about performance so I tested the three suggested methods and timed them in a loop where I log them.
From the looks of it, @Caleb’s
forloop approach might be the best approach to take.