iosswiftnscoding

Saving a custom class into array inside user defaults


Let's say I have a class called Lop. Then I would like to save instances of it to user defaults in some array, and also retrieve objects from this array.

I have created the NSCoding method in that class and now trying to write functions to save/retrieve and having hard time.

To add for example:

   func addLop(newlop:ALop)
    {
        
        //get defaults array(already archived)
        let lops  = NSUserDefaults.standardUserDefaults().objectForKey("lops")
        
        //add a new lop class, archived, to the user defaults array
        let data = NSKeyedArchiver.archivedDataWithRootObject(newlop)
        lops?.addObject(data)
        NSUserDefaults.standardUserDefaults().setObject(lops, forKey: "lops")
        
        
    }

Which I don't really know if works because the retrieve function I just couldn't handle to write:

    func getLops()->Array<Any>
    {
        //get defaults array(archived)
        let lops  = NSUserDefaults.standardUserDefaults().objectForKey("lops")
      
        // here I should loop over this array of archived classes,
        // then turn all of them into original unarchived classes
        // and return
    }
  1. How can I write a function that returns the array of unarchived classes ?

  2. When saving (if done right) how can I check if a class already exist in user defaults before saving?


Solution

    1. With NSKeyedUnarchiver.unarchiveObjectWithData(lops[i] as! NSData)
    2. First you can archive checked object to NSData and then check equality (by calling data.isEqual(lops[i])) of that NSData to each archived NSData you have already stored in NSUserDetaults.

    Other way around is by unarchiving each already stored object from NSUserDefaults and checking equality of ALop objects. You will have to implement bool isEqual(other : NSObject) method in your ALop class and compare in it all properties of two objects, e.g.

    bool isEqual(other : NSObject)
    {
        let otherALop = other as? Alop
        if otherALop == nil {return false }
        if otherALop == self { return true }
    
        bool result = true
        result = result && (self.property == otherALop!.property)
        // ... for all properties repeat previous line 
        return result 
    }
    

    Be aware that NSUserDefaults are limited to store not more than ~64 KB, and are not intended to store your model layer data objects, only app's preferences.