Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 675
Prognastat Avatar asked Mar 13 '13 20:03

Prognastat


2 Answers

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)];
}
like image 123
Hlung Avatar answered Oct 19 '22 21:10

Hlung


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.

like image 41
Scott Berrevoets Avatar answered Oct 19 '22 21:10

Scott Berrevoets