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.
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)];
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With