- I have a UICollectionView with cells that are loading from CoreData.
- User can reorder cells in UICollectionView (it must be reflected in CoreData).
- Cells must be loaded in certain order user saved before.
Q: How to save/load order in CoreData safely (I will add iCloud sync later also)?
- I don't mean overall tips like "add index to entity" or similar. I mean real technique that is 100% stable and ready for synching with iCloud, will not cause any problems and data loss, will not rebuild all data each time etc. Thanks for any help!
- Maybe Core Data has built-in mechanism to handle that. The only thing I've found is ordered one-to-many relationships, but I completely cannot find any detailed info with examples about how it works and even if that's what I am looking for.
hi,
i'm somewhat playing with this right now in a current project, where i have an NSOrderedSet supporting a one-to-many relationship. in my case, it's a high-res image, then one or more thumbnail images for various sizes. so the data for a "Player," say, is defined in the Core Data model, with an relationship "images," a one-to-many with a type "ImageData," where ImageData is really just the data for one image.
Player has this generated variable
var images: NSOrderedSet?
i can add a new Player with this type of code:
let player = Player(context: managedObjectContext)
// fill in some fields
let imageData = ImageData(context: managedObjectContext)
// get some data for the hi-res image
imageData.data = data
player.addToImages(imageData)
// repeat for other images such as thumbnails
let imageData1 = ImageData(context: managedObjectContext)
imageData1.data = data
player.addToImages(imageData1)
// keep on going
i can later retrieve the data using computed properties on Player such as
var photo: UIImage? {
get {
if images!.count == 0 {
return nil
}
let imageData = images![0] as! ImageData // edited after the fact
return UIImage(data: imageData.data!)
}
}
or
var thumbnail: UIImage? {
NSLog("Image count is \(images!.count)")
if images!.count >= 2,
let imageData = images![1] as? ImageData { // edited after the fact
return UIImage(data: imageData.data!)
}
return nil
}
this seems to be working for me (although i too struggled a little with this early on in the process).
when you swap two positions in your CollectionView, you'd have to use other accessors to reorder the NSOrderedSet (don't do it by hand, use the accessors); but, full disclosure, i haven't done this since my data has fixed positions in the NSOrderedSet that are set upon creation
hope that helps,
DMG