-3

Trying to store an array through UserDefault, but Xcode gives me an error. The error message is Thread 1: Signal SIGABRT, and the console says "NSInvalidArgumentException, reason: Attempt to insert non-property list object". I have previously stored data in the array using this code:

let tempRecipe = GlobalFavorites(recipeImageObject: "", recipeTextObject: "", recipeHeaderObject: "", favoriteRecipeArray: [globalFavoriteRecipes])                 

    tempRecipe.recipeHeaderObject = self.recipeClassArray[self.currentView].recipeHeaderObject      

    tempRecipe.recipeTextObject = self.recipeClassArray[self.currentView].recipeTextObject

    tempRecipe.recipeImageObject = self.recipeClassArray[self.currentView].recipeImageObject

    globalFavoriteRecipes.favoriteRecipeArray.append(tempRecipe) 

And that works fine. Here's the code for storing with UserDefault that gives me the error:

UserDefaults.standard.setValue(globalFavoriteRecipes.favoriteRecipeArray, forKey: "savedFavoriteArray")

It's a global array and I want to store the whole array. I guess it has to do with how I write the array in UserDefault, because to me it seems that I'm trying to store something that's not there. Or what am I missing?

Joakim Sjöstedt
  • 824
  • 2
  • 9
  • 18

2 Answers2

0

If globalFavoriteRecipes.favoriteRecipeArray is an array of custom objects, you need to make sure you are archiving and unarchiving them properly. Refer to this StackOverflow post.

That post also touches on some other options, as NSUserDefaults isn't the best place to store an array that can potentially grow pretty large, which it sounds like it could in this case based on the variable name.

Jake G
  • 1,185
  • 9
  • 19
0

Use set not setValue:

UserDefaults.standard.set(globalFavoriteRecipes.favoriteRecipeArray, forKey: "savedFavoriteArray")

But, I agree with @Jake, this should only be used to store small amounts of data, not a large array. Happy coding!

CodeNinja
  • 616
  • 4
  • 18