Prognastat
Prognastat

Reputation: 87

Grab the last x objects from an NSMutableArray

I am trying to grab the last x numbers of objects in an array and store it in another array.

Like this it works:

    NSMutableArray *LastLines = [[LogLines subarrayWithRange:NSMakeRange(0, [LogLines count])] mutableCopy];

However this does not:

NSMutableArray *LastLines = [[LogLines subarrayWithRange:NSMakeRange(([LogLines count]-4), [LogLines count])] mutableCopy];

and the following error shows up in the log:

2013-03-13 15:00:43.475 [38565:303] * -[NSArray subarrayWithRange:]: range {83255, 83259} extends beyond bounds [0 .. 83258]

However the range seems like it should fall within the bounds so I am not sure why it is giving this error.

Upvotes: 9

Views: 4032

Answers (3)

Hlung
Hlung

Reputation: 14308

You can use NSArray -subarrayWithRange: method as other answers suggested, BUT beware if the range exceeds the array count (e.g. getting last 10 line while array only contains 4 elements), it will raise an exception!

To avoid this, simply use an if to check the array count first...

NSArray *logs = <some long array>
int lastLogsCount = 100;
if (logs.count > lastLogsCount) { // check count first to avoid exception
    logs = [logs subarrayWithRange:NSMakeRange(logs.count - lastLogsCount, lastLogsCount)];
}

Upvotes: 7

Scott Berrevoets
Scott Berrevoets

Reputation: 16946

The first one shouldn't work either. Arrays are zero-based, so calling an array's count method will always return one more than the last index that is used. If you change your code to

NSMutableArray *LastLines = [[LogLines subarrayWithRange:NSMakeRange(([LogLines count]-4), 4)] mutableCopy];

it should work. I am not sure why the first line does work, though.

Upvotes: 2

Robert
Robert

Reputation: 5302

If, for example, your array has 10 items, count takes you to position 10. As such an array starts from position zero and extends to position 9, position 10 will be 1 beyond bounds.

Take one away from count to get the last position:

NSMutableArray *LastLines = [[LogLines subarrayWithRange:NSMakeRange(([LogLines count]-4), [LogLines count]-1)] mutableCopy];

Upvotes: 0

Related Questions