I am trying to create a multiple choice test app. I have this code to read off a .txt file:
filePath = [[NSBundle mainBundle] pathForResource:@"testBank" ofType:@"txt"];
theBank = [[NSString alloc] initWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:NULL];
multipleChoicePractice = [theBank componentsSeparatedByString:@"\n"];
The multipleChoicePractice NSMutableArray now contains a bunch of NSStrings in this order:
Question 1
choice A
choice B
choice C
choice D
Answer Key
Rationale
question ID 1
[string to id type of question]
[space 1]
Question 2
choice A-2
etc etc up to Question 10
I am trying to group each index in groups of 10 so that index 0 to 9 of multipleChoicePractice is index 0 of a new mutable array, questionGroupArary. I tried:
for (i=0; i<=90; i = i+10) { //qArr being a NSMutableArray
[qArr addObject:[multipleChoicePractice objectAtIndex:i]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+1)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+2)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+3)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+4)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+5)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+6)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+7)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+8)]];
[qArr addObject:[multipleChoicePractice objectAtIndex:(i+9)]];
[questionGroupArray addObject:qArr];
}
The result of that for loop is that questionGroupArray objectAtIndex: 0 contains EVERYTHING between question 1 and question 10. What is the best way to achieve my goal so that questionGroupArray index 0 contains “question1” to “[space 1]”? I feel like there is a way to do this with a for loop but it escapes me. Thanks!
A much better way to get a subarray of objects in a consecutive range is to use
-[NSArray subarrayWithRange:].