Kodeco Forums

NSCoding Tutorial for iOS: How To Save Your App Data

An NSCoding tutorial on how to quickly and easily save your app's data with NSCoding and NSFileManager in iOS.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3111-nscoding-tutorial-for-ios-how-to-save-your-app-data

I think I must be dense, but I am having a hard time understanding how to store more than one thing at a time in an NSCoder.

My app keeps an internal running history of dice rolls, and what I’m trying to do is enable the saving or loading of saved histories.

I can get one, if I try to store the next, I get a message about the new values clobbering the older ones.

Here’s what I’ve got so far:

func encodeWithCoder(aCoder: NSCoder) {
	for stackItem in 0..<self.abilityScoreHistoryStack.count {
		for roll in 0..<self.abilityScoreHistoryStack[stackItem].rolls.count {
			aCoder.encodeInteger(self.abilityScoreHistoryStack[stackItem].rolls[roll], forKey: PropertyKey.rollsKey)
		aCoder.encodeInteger(self.abilityScoreHistoryStack[stackItem].numberOfDice, forKey: PropertyKey.numDiceKey)
		aCoder.encodeInteger(self.abilityScoreHistoryStack[stackItem].sizeOfDice, forKey: PropertyKey.dieSizeKey)
		aCoder.encodeInteger(self.abilityScoreHistoryStack[stackItem].droppedDice, forKey: PropertyKey.droppedKey)
		aCoder.encodeInteger(self.abilityScoreHistoryStack[stackItem].modifier, forKey: PropertyKey.modKey)
		aCoder.encodeObject(self.abilityScoreHistoryStack[stackItem].itemTitle, forKey: PropertyKey.itemtitleKey)
		aCoder.encodeBool(self.abilityScoreHistoryStack[stackItem].rollSortStatus, forKey: PropertyKey.rollSortStatusKey)

and to trigger it, in the view controller (and triggered by a tap on a button):

@IBAction func saveHistoryButtonAction(sender: UIButton) {
	for _ in 0..<self.charGen.abilityScoreHistoryStack.count {
// MARK: NSCoding
func saveHistory () {
	let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(self.charGen, toFile: CharacterGenerator.ArchiveURL.path!)
	if (!isSuccessfulSave) { print("Save failed. Try something different") }
	// else {  }

I think I understand why I’m getting message that the new values clobber the old, but I am having a devil of a time thinking of another way to handle the fact that there’s an array of these rolls (the history stack is an array of structs defined in the class).

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]