0

I need a class where I can store objects in a stack and when adding one, remove items, which are older than a predefined treshold.

I want to store data each 30 milli seconds in that array (with a timestamp). When adding a new data object I would like to remove all objects which exceed the treshold from their timestamp and the one which was recently added or will be added. I created a class with an array of class DataQueueObject (this class has a variable timestamp).

Now, when pushing a new item, first it checks if there are items in it, then starting from the last, removing it, if it exceeds the maximumQueueTime which is my interval variable

private (set) var objects : [DataQueueObject] = [DataQueueObject](); 
private let maximumQueueTime : Double;

func push(item : DataQueueObjects) {
    while(objects.count > 0) {
        let da : DataQueueObjects = objects.last!;
        if((item.timestamp - da.timestamp) > maximumQueueTime) {
            objects.removeLast()
        }
        else {
            break;
        }
    }
    objects.append(item);
}

My problem now is that sometimes objects.removeLast result in a fatal error:

Array replace: subRange extends past the end

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Vario
  • 490
  • 4
  • 13
  • 1
    I can't reproduce: a loop on `while(objects.count > 0)` where we `removeLast()` doesn't crash for me. Can you provide a complete verifiable working example? – matt Sep 13 '16 at 16:40
  • 3
    Are you calling those methods from multiple threads? – Martin R Sep 13 '16 at 16:41
  • Core Data Concurrency. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/Concurrency.html – antonio081014 Sep 13 '16 at 17:06
  • yes these dataqueues are called from different threads. the data comes from the phones sensors and are sent by nsnotificationscenter.defaultcenter(). a singleton class is listening to these and fills the queue. how can i achieve thread safety in this case? – Vario Sep 13 '16 at 18:20
  • See http://stackoverflow.com/questions/28191079/create-thread-safe-array-in-swift or http://stackoverflow.com/questions/28784507/adding-items-to-swift-array-across-multiple-threads-causing-issues-because-arra. – Martin R Sep 13 '16 at 18:38
  • based on these links from Martin R a objc_sync_enter(lock) at the beginning and objc_sync_exit(lock) at the end of the method would fix that problem? – Vario Sep 13 '16 at 20:36

0 Answers0