I have an array with 32 objects inside. I am currently trying to figure out a way in which I can display only certain objects inside the array on my page. For example I want to display objects within index 10-18 only. I tried slicing the array to add the range and it works but the problem is, I can’t have any of the objects repeat on the same page. So if the objects to be displayed are only 10-18, each object should only be displayed once and in random order so here’s how the code I tried looks:
NSArray *slice;
slice = [arrayList subarrayWithRange:NSMakeRange(5,7)];
int i = arc4random() % [slice count];
int k = arc4random() % [slice count];
int j = arc4random() % [slice count]
[self.btnRand1 setTitle:[slice objectAtIndex: i] forState:UIControlStateNormal];
[arrayList removeObjectAtIndex:i];
[self.btnRand2 setTitle:[slice objectAtIndex: j] forState:UIControlStateNormal];
[arrayList removeObjectAtIndex:j];
[self.btnRand3 setTitle:[slice objectAtIndex: k] forState:UIControlStateNormal];
[arrayList removeObjectAtIndex:k];
I need the removeObjectAtIndex to remove the objects that have already been used within the array, but given that I’m using slice to select objects within a certain objects only, it does not work and certain objects would be repeated within the range. And as I’ve read, you can’t use it for NSArrays at all.
How can I add a range for this that won’t repeat any of the objects within selected range?
You need to make slice a mutable array. You get your first random index, then delete that entry from the array. Repeat that as many times as you want, up to the number of items in slice.