I want to randomly display some images stored as attributes on an entity "Disc" in Core Data. I've been using the Swift Array.shuffled()
function performed on the fetchedObjects
of my NSFetchedResultsController
"thisFRC.
"
First problem was that the desired images often did not appear when they should. Here's code that produced this problem. It's part of a function loadImages
, which is called from viewWillAppear
:
try thisFRC.performFetch()
fetchedData = thisFRC.fetchedObjects as! [Disc]
shuffledDiscs = fetchedData.shuffled()
thisDisc = shuffledDiscs [0]
Second problem was that when they did appear, I would very often see the same image repeated several (or many) times. I thought maybe the images were persisting for some unknown reason, so I did:
frontImageView.image = nil
rearImageView.image = nil
in prepareForSegue
. Same problem upon returning to the original View Controller.
Third problem arose when I tried to fix the second problem by further randomizing the order of the images with the code below. It crashes at the commented line with this error: “Index out of range”.
try thisFRC.performFetch()
fetchedData = thisFRC.fetchedObjects as! [Disc]
shuffledIndices = fetchedData.indices.shuffled()
index = shuffledIndices [0] // Crashes here with “Index out of range”
shuffledDiscs = fetchedData.shuffled()
thisDisc = shuffledDiscs [index]
My questions:
1) Why doesn't the shuffled()
function do a better job of randomizing? To be fair, I tried this code in a separate test app, and it seemed to work fine. If I can clear this up, I can dispense with my workaround.
2) I don't understand how the index could be out of range in index = shuffledIndices [0]
Note:
The images I'm using are quite large -- on the order of 2400 x 2400 -- being squeezed into a 160 x 160 image view, so the early anomalies could possibly be caused by scaling.
Any help would be greatly appreciated!
TIA
Resolved!
With insight from @Adis, and a thousand print()
lines, I discovered the problem:
There was a function extraneously inserting a new Disc entity into my context every time I segued to one of the two connected View Controllers. This accounted for the "ghost" items that were showing up with no UIImage
attributes, creating blank ImageViews. Once I deleted these anomalies, and killed the function that created them, everything works fine. I was also able to just use the shuffled()
function without the extra flourish I had put on it.
All is well, and thanks to all who took the time to look!