I have this curious thinf happening here where tempArray is supposed to be added to the masterArray each time the if statement occurs. (The if statement works perfectly and gets triggered when it should.)
I also need to clear the temp array each time it does.
My final result should then be a masterarray which contains each array it has added.(meaning all the temp arrays that I have added throughout the for loop)
Instead, it only keeps adding the tempArray to the MasterArray at index 0 every single time.
Code:
- (void)alpabetize:(NSArray *)arr {
self.tempArray = [[NSMutableArray alloc] init];
self.masterArray = [[NSMutableArray alloc] init];
for (int i = 0; i<[arr count]; i++) {
NSString *currentString = [NSString stringWithFormat:@"%@", [[[arr objectAtIndex:i] valueForKey:@"first_name"] substringToIndex:1]];
NSString *nextString = [NSString stringWithFormat:@"%@", [[[arr objectAtIndex:(i+1)] valueForKey:@"first_name"] substringToIndex:1]];
[self.tempArray addObject:[arr objectAtIndex:i]];
if (![currentString isEqualToString:nextString]) {
[self.masterArray addObject:tempArray];
[self.tempArray removeAllObjects];
}
}
}
If you remove all objects from the original array previously added to some other array. Does this also clear the other array? This makes no sense to me. There must be something wrong in my code. Can somebody help me spot my error?
Thank you for your time!
Use
or
instead of
In your code you are adding the reference of the same array which you are clearing in next statement.