2

My first post in SE so please go gently on me.... :)

I'm new to swift and iOS dev but have been learning over the last few months.

I have an app that I use to hold dates and values via NSCoder and encodeObjectForKey. I pass NSDate values into this and can decode them with no issues.

However, if I try to pass in nil to overwrite the existing value it appears this is not stored because the old value is returned after the value is decoded and returned.

I searched and found that passing nil to the encodeObjectForKey method appears to be valid, but I can't find anything that tells me if this will work when overworking an existing value with nil.

Can anyone provide guidance on how to delete the existing value?

My code:

aCoder.encodeObject(dateSold, forKey: PropertyKey.dateSoldKey)    
let dateSold = aDecoder.decodeObjectForKey(PropertyKey.dateSoldKey) as? NSDate

Edit: Seems my updated date value of Nil is not making it back across the segue to the class which saves the updates and calls the encodeObject. I shall go and investigate. Apologies for the time wasting....

UKDevBloke
  • 21
  • 3

1 Answers1

0

I think that, while decoding you can check whether the object is equal to the previous object or not. If the object is equal to previous object make it nil.

//: Playground - noun: a place where people can play

import UIKit
import Foundation

class Dates : NSObject
{
    //MARK: Local Variables

    var createdAt: NSDate?
    var previoudDate : NSDate?

    required convenience init(coder decoder: NSCoder)
    {
        self.init()

        if let proper_CreatedAt = decoder.decodeObjectForKey("YourKey") as? NSDate {

            if let proper_previousDate = self.previoudDate where proper_previousDate == proper_CreatedAt
            {
                decoder.encodeObject(nil, forKey: "YourKey")
                self.createdAt = nil
                self.previoudDate = nil
            }
            else
            {
                self.createdAt = proper_CreatedAt
                self.previoudDate = proper_CreatedAt
            }
        }
        else {
            decoder.encodeObject(nil, forKey: "YourKey")
        }
    }

    convenience init(createdAt : NSDate?)
    {
        self.init()
        self.createdAt = createdAt
    }

    func encodeWithCoder( coder : NSCoder)
    {
         if let proper_previousDate = self.createdAt
        {
        coder.encodeObject(proper_previousDate, forKey: "YourKey")
        }
    }
}

let kk = Dates()
kk.createdAt = NSDate()
print(kk.createdAt)

Also found two methods which may help you out a lil bit for solving this,

decoder.replacementObjectForCoder(NSCoder)
decoder.replacementObjectForKeyedArchiver(NSKeyedArchiver)

But these takes an input type of NSCoder & NSKeyedArchiver, not a key.