iPhoneCache - Kelmatou/iOSTools GitHub Wiki

Properties

  • var ArchiveURL: URL?

Inits

  • init(filename: String)
  • init?(coder aDecoder: NSCoder)

Methods

  • func encode(with aCoder: NSCoder)
  • func saveObject() -> Bool

Statics

  • func loadObject<T>(from file: String) -> T?
  • func saveBasicObject(_ object: Any?, withKey: String)
  • func loadBasicObject(withKey: String) -> Any?

Definitions

  • var ArchiveURL: URL?: A file path where object will be saved. Be careful when you modify this value directly as it may result in overriding an existing file.

  • init(filename: String): Create a SavableObject that will be saved in filename.

  • init?(coder aDecoder: NSCoder): Called when reloading an object from file. Override this method if your object needs to be recovered at any point. See example section.

  • func encode(with aCoder: NSCoder): Called when saving object to file. Override this method if your object needs to be saved at any point. See example section.

  • func saveObject() -> Bool: Save current object to ArchiveURL using encode(aCoder:). Return true if object was successfully saved, false if an error occurred.

  • static func loadObject<T>(from file: String) -> T?: Load and return an object from file. nil is returned if object loading failed.

  • static func saveBasicObject(_ object: Any?, withKey: String): Quickly save native type such as String, Int... using withKey to recover the value later. Calling this method with a more complex type will result in a crash.

  • static func loadBasicObject(withKey: String) -> Any?: Quickly recover native type such as String, Int... using withKey. Calling this method with a more complex type will result in a crash.


Example

  class A: SavableObject {
    
    var a: Int?
    var b: String?
    static let aKey: String = "intKey"
    static let bKey: String = "stringKey"
    public static let filename: String = "AObject"
    
    init(a: Int) {
      super.init(filename: A.filename)
      self.a = a
      self.b = "\(a)"
    }
    init(a: Int?, b: String?) {
      super.init(filename: A.filename)
      self.a = a
      self.b = b
    }
    
    override func encode(with aCoder: NSCoder) {
      aCoder.encode(a, forKey: A.aKey)
      aCoder.encode(b, forKey: A.bKey)
    }
    
    required convenience init?(coder aDecoder: NSCoder) {
      let a = aDecoder.decodeObject(forKey: A.aKey) as? Int
      let b = aDecoder.decodeObject(forKey: A.bKey) as? String
      guard let aUnwrapped = a, let bUnwrapped = b else {
        return nil
      }
      self.init(a: aUnwrapped, b: bUnwrapped)
    }
  }

  let object: A = A(a: 42) // Create a custom object A: SavableObject
  object.saveObject() // Saving object
  let object2: A? = A.loadObject(from: A.filename) // Recreating object in object2
  // object2?.a = 42
  // object2?.b = "42"