Save an array of colors to User Defaults - iOS Swift 2.3












1















I am wondering how to save an array of UIColors to user default.



I have the following code to save a single UIColor to user defaults, does anyone know how to modify this to allow me to store arrays of UIColor in NS User Defaults?






extension NSUserDefaults {

func colorForKey(key: String) -> UIColor? {
var color: UIColor?
if let colorData = dataForKey(key) {
color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
}
return color
}



func setColor(color: UIColor?, forKey key: String) {
var colorData: NSData?
if let color = color {
colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
}
setObject(colorData, forKey: key)
}

}






  • I am using Swift 2.3










share|improve this question



























    1















    I am wondering how to save an array of UIColors to user default.



    I have the following code to save a single UIColor to user defaults, does anyone know how to modify this to allow me to store arrays of UIColor in NS User Defaults?






    extension NSUserDefaults {

    func colorForKey(key: String) -> UIColor? {
    var color: UIColor?
    if let colorData = dataForKey(key) {
    color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
    }
    return color
    }



    func setColor(color: UIColor?, forKey key: String) {
    var colorData: NSData?
    if let color = color {
    colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
    }
    setObject(colorData, forKey: key)
    }

    }






    • I am using Swift 2.3










    share|improve this question

























      1












      1








      1


      1






      I am wondering how to save an array of UIColors to user default.



      I have the following code to save a single UIColor to user defaults, does anyone know how to modify this to allow me to store arrays of UIColor in NS User Defaults?






      extension NSUserDefaults {

      func colorForKey(key: String) -> UIColor? {
      var color: UIColor?
      if let colorData = dataForKey(key) {
      color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
      }
      return color
      }



      func setColor(color: UIColor?, forKey key: String) {
      var colorData: NSData?
      if let color = color {
      colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
      }
      setObject(colorData, forKey: key)
      }

      }






      • I am using Swift 2.3










      share|improve this question














      I am wondering how to save an array of UIColors to user default.



      I have the following code to save a single UIColor to user defaults, does anyone know how to modify this to allow me to store arrays of UIColor in NS User Defaults?






      extension NSUserDefaults {

      func colorForKey(key: String) -> UIColor? {
      var color: UIColor?
      if let colorData = dataForKey(key) {
      color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
      }
      return color
      }



      func setColor(color: UIColor?, forKey key: String) {
      var colorData: NSData?
      if let color = color {
      colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
      }
      setObject(colorData, forKey: key)
      }

      }






      • I am using Swift 2.3






      extension NSUserDefaults {

      func colorForKey(key: String) -> UIColor? {
      var color: UIColor?
      if let colorData = dataForKey(key) {
      color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
      }
      return color
      }



      func setColor(color: UIColor?, forKey key: String) {
      var colorData: NSData?
      if let color = color {
      colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
      }
      setObject(colorData, forKey: key)
      }

      }





      extension NSUserDefaults {

      func colorForKey(key: String) -> UIColor? {
      var color: UIColor?
      if let colorData = dataForKey(key) {
      color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
      }
      return color
      }



      func setColor(color: UIColor?, forKey key: String) {
      var colorData: NSData?
      if let color = color {
      colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
      }
      setObject(colorData, forKey: key)
      }

      }






      ios swift nsuserdefaults






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 18 '16 at 14:49









      Jerland2Jerland2

      512319




      512319
























          2 Answers
          2






          active

          oldest

          votes


















          6














          You can do it in following way



          let colors = [UIColor.whiteColor(), UIColor.greenColor()] // Array of colors
          NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(colors), forKey: "ColorsKey") //For saving in NSUserDefaults
          //For retrieving use following
          let decodedColorsData = NSUserDefaults.standardUserDefaults().objectForKey("ColorsKey") as! NSData
          let colorsArray = (NSKeyedUnarchiver.unarchiveObjectWithData(decodedColorsData) as! NSArray) as Array





          share|improve this answer
























          • Thank you, this works perfectly!

            – Jerland2
            Jun 18 '16 at 16:12



















          0














          Swift 4.2: Saving and loading colours / colours to user defaults
          note: the load from defaults works but contains a deprecated item which does not yet have a good worked example to replace it.



                         let colorToSetAsDefault : UIColor = view.backgroundColor!
          do
          {
          let data : NSData = try NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault,requiringSecureCoding: false) as NSData
          UserDefaults.standard.set(data, forKey: "userHeadingColor") // your key in quotes
          UserDefaults.standard.synchronize()
          } // end of do
          catch
          {
          print("Couldn't save color")
          } // end of catch

          // load the color back as a test to make sure the save has worked
          if let colorObject = UserDefaults.standard.object(forKey: "userHeadingColor")
          {
          let colorData = colorObject as! NSData
          let color = NSKeyedUnarchiver.unarchiveObject(with: colorData as Data) as? UIColor
          // replace with unarchivedObjectOfClass:fromData:error:
          self.testDefaultsView.backgroundColor = color
          }
          else
          {

          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37898250%2fsave-an-array-of-colors-to-user-defaults-ios-swift-2-3%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            You can do it in following way



            let colors = [UIColor.whiteColor(), UIColor.greenColor()] // Array of colors
            NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(colors), forKey: "ColorsKey") //For saving in NSUserDefaults
            //For retrieving use following
            let decodedColorsData = NSUserDefaults.standardUserDefaults().objectForKey("ColorsKey") as! NSData
            let colorsArray = (NSKeyedUnarchiver.unarchiveObjectWithData(decodedColorsData) as! NSArray) as Array





            share|improve this answer
























            • Thank you, this works perfectly!

              – Jerland2
              Jun 18 '16 at 16:12
















            6














            You can do it in following way



            let colors = [UIColor.whiteColor(), UIColor.greenColor()] // Array of colors
            NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(colors), forKey: "ColorsKey") //For saving in NSUserDefaults
            //For retrieving use following
            let decodedColorsData = NSUserDefaults.standardUserDefaults().objectForKey("ColorsKey") as! NSData
            let colorsArray = (NSKeyedUnarchiver.unarchiveObjectWithData(decodedColorsData) as! NSArray) as Array





            share|improve this answer
























            • Thank you, this works perfectly!

              – Jerland2
              Jun 18 '16 at 16:12














            6












            6








            6







            You can do it in following way



            let colors = [UIColor.whiteColor(), UIColor.greenColor()] // Array of colors
            NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(colors), forKey: "ColorsKey") //For saving in NSUserDefaults
            //For retrieving use following
            let decodedColorsData = NSUserDefaults.standardUserDefaults().objectForKey("ColorsKey") as! NSData
            let colorsArray = (NSKeyedUnarchiver.unarchiveObjectWithData(decodedColorsData) as! NSArray) as Array





            share|improve this answer













            You can do it in following way



            let colors = [UIColor.whiteColor(), UIColor.greenColor()] // Array of colors
            NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(colors), forKey: "ColorsKey") //For saving in NSUserDefaults
            //For retrieving use following
            let decodedColorsData = NSUserDefaults.standardUserDefaults().objectForKey("ColorsKey") as! NSData
            let colorsArray = (NSKeyedUnarchiver.unarchiveObjectWithData(decodedColorsData) as! NSArray) as Array






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jun 18 '16 at 15:06









            Vishnu gondlekarVishnu gondlekar

            3,1801128




            3,1801128













            • Thank you, this works perfectly!

              – Jerland2
              Jun 18 '16 at 16:12



















            • Thank you, this works perfectly!

              – Jerland2
              Jun 18 '16 at 16:12

















            Thank you, this works perfectly!

            – Jerland2
            Jun 18 '16 at 16:12





            Thank you, this works perfectly!

            – Jerland2
            Jun 18 '16 at 16:12













            0














            Swift 4.2: Saving and loading colours / colours to user defaults
            note: the load from defaults works but contains a deprecated item which does not yet have a good worked example to replace it.



                           let colorToSetAsDefault : UIColor = view.backgroundColor!
            do
            {
            let data : NSData = try NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault,requiringSecureCoding: false) as NSData
            UserDefaults.standard.set(data, forKey: "userHeadingColor") // your key in quotes
            UserDefaults.standard.synchronize()
            } // end of do
            catch
            {
            print("Couldn't save color")
            } // end of catch

            // load the color back as a test to make sure the save has worked
            if let colorObject = UserDefaults.standard.object(forKey: "userHeadingColor")
            {
            let colorData = colorObject as! NSData
            let color = NSKeyedUnarchiver.unarchiveObject(with: colorData as Data) as? UIColor
            // replace with unarchivedObjectOfClass:fromData:error:
            self.testDefaultsView.backgroundColor = color
            }
            else
            {

            }





            share|improve this answer




























              0














              Swift 4.2: Saving and loading colours / colours to user defaults
              note: the load from defaults works but contains a deprecated item which does not yet have a good worked example to replace it.



                             let colorToSetAsDefault : UIColor = view.backgroundColor!
              do
              {
              let data : NSData = try NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault,requiringSecureCoding: false) as NSData
              UserDefaults.standard.set(data, forKey: "userHeadingColor") // your key in quotes
              UserDefaults.standard.synchronize()
              } // end of do
              catch
              {
              print("Couldn't save color")
              } // end of catch

              // load the color back as a test to make sure the save has worked
              if let colorObject = UserDefaults.standard.object(forKey: "userHeadingColor")
              {
              let colorData = colorObject as! NSData
              let color = NSKeyedUnarchiver.unarchiveObject(with: colorData as Data) as? UIColor
              // replace with unarchivedObjectOfClass:fromData:error:
              self.testDefaultsView.backgroundColor = color
              }
              else
              {

              }





              share|improve this answer


























                0












                0








                0







                Swift 4.2: Saving and loading colours / colours to user defaults
                note: the load from defaults works but contains a deprecated item which does not yet have a good worked example to replace it.



                               let colorToSetAsDefault : UIColor = view.backgroundColor!
                do
                {
                let data : NSData = try NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault,requiringSecureCoding: false) as NSData
                UserDefaults.standard.set(data, forKey: "userHeadingColor") // your key in quotes
                UserDefaults.standard.synchronize()
                } // end of do
                catch
                {
                print("Couldn't save color")
                } // end of catch

                // load the color back as a test to make sure the save has worked
                if let colorObject = UserDefaults.standard.object(forKey: "userHeadingColor")
                {
                let colorData = colorObject as! NSData
                let color = NSKeyedUnarchiver.unarchiveObject(with: colorData as Data) as? UIColor
                // replace with unarchivedObjectOfClass:fromData:error:
                self.testDefaultsView.backgroundColor = color
                }
                else
                {

                }





                share|improve this answer













                Swift 4.2: Saving and loading colours / colours to user defaults
                note: the load from defaults works but contains a deprecated item which does not yet have a good worked example to replace it.



                               let colorToSetAsDefault : UIColor = view.backgroundColor!
                do
                {
                let data : NSData = try NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault,requiringSecureCoding: false) as NSData
                UserDefaults.standard.set(data, forKey: "userHeadingColor") // your key in quotes
                UserDefaults.standard.synchronize()
                } // end of do
                catch
                {
                print("Couldn't save color")
                } // end of catch

                // load the color back as a test to make sure the save has worked
                if let colorObject = UserDefaults.standard.object(forKey: "userHeadingColor")
                {
                let colorData = colorObject as! NSData
                let color = NSKeyedUnarchiver.unarchiveObject(with: colorData as Data) as? UIColor
                // replace with unarchivedObjectOfClass:fromData:error:
                self.testDefaultsView.backgroundColor = color
                }
                else
                {

                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 12:09









                SundialSoftSundialSoft

                816




                816






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37898250%2fsave-an-array-of-colors-to-user-defaults-ios-swift-2-3%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Create new schema in PostgreSQL using DBeaver

                    Deepest pit of an array with Javascript: test on Codility

                    Costa Masnaga