Grab the last x objects from an NSMutableArray
cocoa, nsarray, objective-c
Solution
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)];
}
Problem
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.