Michael
Michael

Reputation: 811

NSArray: Removing every element but the first 20

I have a NSArray with possibly hundreds of elements. I want to remove every element but the 20 first ones. Ideas?

Upvotes: 2

Views: 2051

Answers (3)

rdelmar
rdelmar

Reputation: 104082

If your array is an NSArray, then you can't remove objects since it's immutable. You'll need to do something like Neo's answer. If your array is an NSMutableArray, you can use the following line to get the first 20 items:

[myArray removeObjectsInRange:NSMakeRange(20, myArray.count - 20)];

Upvotes: 5

Neo
Neo

Reputation: 2807

Suppose your NSArray is yourArray, do this

NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:yourArray];
for(int i=0; i<20;i++){
    [temp addObject:[yourArray objectAtIndex:i]];
}
yourArray=[NSArray arrayWithArray:temp];

Upvotes: 0

Cyrille
Cyrille

Reputation: 25144

You can extract the first 20 items, and re-assign your source array:

NSArray *myHugeArray = [[NSArray alloc] initWithItems:...] // An array with, say, 1000 items
NSArray *tmpArray = [myHugeArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 20)]];
[myHugeArray release];
myHugeArray = [tmpArray retain];

Upvotes: 1

Related Questions