Grab the latest x objects from NSMutableArray

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

How it works:

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

However, it is not:

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

and the following error appears in the log:

2013-03-13 15: 00: 43.475 [38565: 303] * - [Subarray NSArrayWithRange:]: the range {83255, 83259} is outside the range [0 .. 83258]

However, the range seems like it should fall within the boundaries, so I'm not sure why it is giving this error.

+7
source share
3 answers

You can use the NSArray -subarrayWithRange: method as other suggested answers BUT , if the range exceeds the number of arrays (for example, getting the last 10 rows while the array contains only 4 elements), this will throw an exception

To avoid this, simply use if to first check the number of arrays ...

 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)]; } 
+3
source

The first one should not work either. Arrays are zero-based, so calling the count array method will always return one more than the last used index. If you change your code to

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

he should work. I'm not sure why the first line works.

+2
source

If, for example, your array has 10 elements, count will take you to position 10. Since such an array starts at position zero and continues to position 9, position 10 will be 1 outside the borders.

Remove one of the counters to get the last position:

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

All Articles