0

Basically, I want to have an NSMutableArray, but only allow it to have 5 items. If I add a sixth, the oldest item in the array gets removed.

Would I be best off just subclassing NSMutableArray and checking this in addObject then using removeObjectsInRange or is there a better solution?

bneely
  • 9,083
  • 4
  • 38
  • 46
Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • 2
    [`NSCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSCache_Class/Reference/Reference.html#//apple_ref/occ/instm/NSCache/setCountLimit:) will take a count limit, but it's not ordered. Much easier to _compose_ `NSMutableArray` with a new class that manages it than to subclass it. – jscs Apr 11 '14 at 20:03

3 Answers3

2

If you want to be strictly time ordered from newest to oldest, then a concise way is to add like this. (without need to subclass, just always add this way)...

- (void)fifoAddObject:(id)object {
    // self.queue is a mutable array
    [self.queue insertObject:object atIndex:0];
    if (self.queue.count > MAX_ALLOWED_COUNT) [self.queue removeLastObject];
}
danh
  • 62,181
  • 10
  • 95
  • 136
0

It seems that you may need a queue (http://en.wikipedia.org/wiki/Queue_(abstract_data_type)

You can find possible implementation here How do I make and use a Queue in Objective-C? (it uses MRC. You will need to remove all "retain" and "autorelease" if you are using MRC)

Community
  • 1
  • 1
Avt
  • 16,927
  • 4
  • 52
  • 72
0

Here's how I would do it.

Create a queue. In that queue, all you do is

  1. Check the size of the array
  2. if equal to 5, remove and add the current one
  3. else just add the object

Then everywhere in your code when you want to add an object to the array, you just add the object to the queue.

This way, you have some kind of locking method, where only one person is trying to add and remove objects from the array, so you can check size before doing any of this.

good luck!

user3339357
  • 292
  • 3
  • 16