core data index changing during touches
<p>I've got a SpriteKit app using Core Data.  The main GameScene holds a number of sprites (15 or so). Of these, there are 3 sprites with special characteristics (e.g. name, color, type and description).  The sprites are picked up from the Core Data store in viewDidLoad().</p>

<pre><code>import SpriteKit
import UIKit
import CoreData
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        // Background, some other sprites loaded, set-up physics world
        ...
        // MARK: get stored data from Core Data
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = appDelegate.managedObjectContext
        let request = NSFetchRequest(entityName: projectEntityName)

        do {
            let objectList = try context.executeFetchRequest(request)
            for oneObject in objectList {
                let spriteNode = SKSpriteNode(color: SKColor(red:(CGFloat(oneObject.valueForKey(redKey)!.floatValue), green: CGFloat(oneObject.valueForKey(greenKey)!.floatValue), blue: CGFloat(oneObject.valueForKey(blueKey)!.floatValue), alpha: 1),  size: CGSizeMake(10, 10)
            // set some extensions
            spriteNode.name = oneObject.valueForKey(nameKey) as! String
            spriteNode.type = oneObject.valueForKey(typeKey) as! String
            spriteNode.description = oneObject.valueForKey(descriptionKey) as! String
        }

        // helper class to show what is happening in Core Data store (just more oneObject.valueForKey calls which are printed to see what value is stored)
        let projectProblem = ProjectProblem()
        projectProblem.projectDescriptionProblem()
    }

    override func touchesBegan(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) {
        print("touchesBegan")
        if let touch = touches.first {
            touchStart = touch.locationInNode(self)
            // helper class again
            let projectProblem = ProjectProblem()
            projectProblem.projectDescriptionProblem()
        }
    }


    override func touchesMoved(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) {
    }


    override func touchesCancelled(touches: Set&lt;UITouch&gt;?, withEvent event: UIEvent?) {
    print("touchesCancelled")
    if let touch = touches!.first, start = touchStart {
        let location = touch.locationInNode(self)
        // Compute the distance between the two touches
        let dx = location.x - start.x
        let dy = location.y - start.y
        distance = sqrt(dx*dx + dy*dy)
        if distance &lt; minSwipeDistance {
            let node = nodeAtPoint(location)
            if node.name == "node1" {
                // helper class called again
                let projectProblem = ProjectProblem()
                projectProblem.projectDescriptionProblem()
                let transition = SKTransition.crossFadeWithDuration(StandardSettings.SceneManager.transitionDuration)
                let nextScene = NextScene(size: self.frame.size)
                nextScene.scaleMode = .AspectFill
                view?.presentScene(nextScene, transition: transition)
            } else if node.name == "node2" {
                // transition to another scene (and run helper)
            } else etc....
        }
    }

    override func touchesEnded(touches: Set&lt;UITouch&gt;?, withEvent event: UIEvent?) {
        print("touchesEnded")
      // same code as touchesCancelled
    }
}
</code></pre>

<p>For troubleshooting purposes, I've set up some additional labels in the scene and, as I've shown here, a helper class to read what is stored in core data.  I've used this helper class in different locations.  The reason for this helper class is that the contents of one of the data store records is getting moved around to another entry (the "description" field).  As I'm not setting their values in this part of my code, nothing should change and for all the other stored fields, nothing changes in the store.  They stay the same.  </p>

<p>Each time when I perform a touch on a node, the "description" field reading from the data store looks like this (with it's corresponding record entry):</p>

<pre><code>1st run    didMoveToView()    touchesBegan()    touchesCancelled/Ended()

1          "node is A"        "..C", "..C"          "node is A"

2          "node is B"        "..A", "..A"          "node is B"

3          "node is C"        "..B", "..B"          "node is C"


2nd run    didMoveToView()    touchesBegan()    touchesCancelled/Ended()

1          "node is A"        "..A", "C", "C"       "node is C"

2          "node is B"        "..B", "B", "B"       "node is A"

3          "node is C"        "..B"  "A", "A"       "node is B"


3rd run    didMoveToView()    touchesBegan()    touchesCancelled/Ended()

1          "node is C"         "C", "C", "C"         "node is A"

2          "node is A"         "A", "B", "B"         "node is B"

3          "node is B"         "B", "A", "A"         "node is C"
</code></pre>

<p>This is just to give a flavour of what is happening, but I haven't found a pattern yet, except that the problem seems to start when touchesBegan() is called.  The reason for multiple records under touchesBegan() is that there are anything between 1 and 4 results being returned on touchesBegan(), before a result is returned from touchesCancelled or touchesEnded().  It's only this one attribute that's getting moved around. </p>

<p>Once didMoveToView has run, the records are where they should be in the store.  This problem then sometimes affects the record corresponding to the node that is touched, sometimes just the other records or sometimes all three.  While I have seen duplicate records in touchesBegan(), I've never seen any duplicates subsequently in touchesCancelled() or touchesEnded(), just that the records have moved to the wrong location.  I've looked everywhere else in my app for similar problems but the rest is stable.  I've reproduced this problem on both the simulator and on an iPhone.  I've also reset the simulator and performed a clean and build on the application.  Still the same problem. </p>

<p>The ProjectProblem class looks like this:</p>

<pre><code>import UIKit
import CoreData

class ProjectProblem {
    func projectDescriptionProblem () {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = appDelegate.managedObjectContext
        let request = NSFetchRequest(entityName: projectEntityName)
        do {
            let objectList = try context.executeFetchRequest(request)
            for thisObject in objectList {
                print("DESCRIPTION: \(thisObject.valueForKey(descriptionKey) as! String)")
            }
        }
        catch _ as NSError {
           print("descriptionError")
        }
    }
}
</code></pre>

<p>Has anyone any ideas what I can do to troubleshoot and fix this?  </p>

<p><strong>UPDATE:</strong>
I've run numerous simulations and changed the way any <code>setValue</code> writes to the "description" field are performed in other scenes.  I've discovered two things.
1) changing the way writes are done elsewhere in my code results in an improvement.  Now only the last record in the data store is changing without a <code>setValue</code> being called.  The scenes where writes are performed are closed and the GameScene is in a stable situation once it has loaded, but somewhere there are core data write actions hanging around in the background.  When touches are called in the GameScene, these are triggered.  As a rule of thumb, the earlier writes to core data are done in code, the better (i.e. well before a transition away from that scene).<br>
2) even though things have improved there is still a problem; the last record in the data store is still changing without <code>setValue</code> being called.  What happens is best described as follows:</p>

<pre><code>e.g. 5 nodes, numbered 1 to 5; each node corresponds to a different core data entry ('A', 'B', 'C', 'D', 'E', respectively).
- touch node_1 and nothing happens to the records in the data store; they stay the same which is what they should do as I don't do any new writes to the data store
- touch node_2 and 'E' is replaced in the final record (the one corresponding to node 5) with 'A'; the first 4 entries stay the same (so it looks like ('A', 'B', 'C', 'D', 'A') now)
- touch node_3 and 'A' is replaced in the final record with 'B'; again the others stay the same ('A', 'B', 'C', 'D', 'B')
- touch node_4 and 'B' is replaced in the final record with 'C' ('A', 'B', 'C', 'D', 'C')
- touch node_5, which corresponds with entry 5 and 'C' becomes 'D' ('A', 'B', 'C', 'D', 'D')
- touch any other node again and the entry in the final record stays the same ('A', 'B', 'C', 'D', 'D')
</code></pre>

<p>Basically the record is changing to the same entry as another in the data store (including it's own).  It's not the entry corresponding to the node being touched, it's the one corresponding to the node touched immediately before it.</p>

<p>I suspect there is some latency in the way writes are made to the data store, which other parts of the code can overtake (such as a transition away from a scene).  This is possibly leaving a "write-thread" open somewhere.  The setValue remains open before the cycle <code>do {... let objectList... for thisObject in...</code> are finished.  These are then called from the core data stack the next time an action takes place in the application.  If this is the case, has anyone experience of something similar, how to find these, or better still, purge them from the code?</p>