iOS 设计模式-- 备忘录模式 - Memento

备忘录模式捕捉并且具象化一个对象的内在状态。换句话说,它把你的对象存在了某个地方,然后在以后的某个时间再把它恢复出来,而不会打破它本身的封装性,私有数据依旧是私有数据。

如何使用备忘录模式

NSUserDefaults

func saveCurrentState() {
  NSUserDefaults.standardUserDefaults().setInteger(currentAlbumIndex, forKey: "currentAlbumIndex")
}

func loadPreviousState() {
  currentAlbumIndex = NSUserDefaults.standardUserDefaults().integerForKey("currentAlbumIndex")
}

归档 - Archiving

苹果通过归档的方法来实现备忘录模式。它把对象转化成了流然后在不暴露内部属性的情况下存储数据

如何使用归档

//首先,我们需要让 Album 实现 NSCoding 协议,声明这个类是可被归档的。
class Album: NSObject, NSCoding {
  //解档
  required init(coder decoder: NSCoder)   {
      super.init()
      self.title = decoder.decodeObjectForKey("title") as String?
      self.artist = decoder.decodeObjectForKey("artist") as String?
      self.genre = decoder.decodeObjectForKey("genre") as String?
      self.coverUrl = decoder.decodeObjectForKey("cover_url") as String?
      self.year = decoder.decodeObjectForKey("year") as String?
  }

  //归档
  func encodeWithCoder(aCoder: NSCoder) {
      aCoder.encodeObject(title, forKey: "title")
      aCoder.encodeObject(artist, forKey: "artist")
      aCoder.encodeObject(genre, forKey: "genre")
      aCoder.encodeObject(coverUrl, forKey: "cover_url")
      aCoder.encodeObject(year, forKey: "year")
  }
}

PersistencyManager.swift

//归档保存本地
func saveAlbums() {
    var filename = NSHomeDirectory().stringByAppendingString("/Documents/albums.bin")
    let data = NSKeyedArchiver.archivedDataWithRootObject(albums)
    data.writeToFile(filename, atomically: true)
} 

override init() {
    super.init()
    if let data = NSData(contentsOfFile: NSHomeDirectory().stringByAppendingString("/Documents/albums.bin")) {
        //解档还原数据
        let unarchiveAlbums = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Album]?
        if let unwrappedAlbum = unarchiveAlbums {
            albums = unwrappedAlbum
        }
    } else {
        //失败创建新的对象
        createPlaceholderAlbum()
    }
}

func createPlaceholderAlbum() {
    //Dummy list of albums
    let album1 = Album(title: "Best of Bowie",
             artist: "David Bowie",
             genre: "Pop",
             coverUrl: "http://www.coversproject.com/static/thumbs/album/album_david%20bowie_best%20of%20bowie.png",
             year: "1992")

    let album2 = Album(title: "It's My Life",
           artist: "No Doubt",
           genre: "Pop",
           coverUrl: "http://www.coversproject.com/static/thumbs/album/album_no%20doubt_its%20my%20life%20%20bathwater.png",
           year: "2003")

    let album3 = Album(title: "Nothing Like The Sun",
               artist: "Sting",
           genre: "Pop",
           coverUrl: "http://www.coversproject.com/static/thumbs/album/album_sting_nothing%20like%20the%20sun.png",
           year: "1999")
    albums = [album1, album2, album3]
    saveAlbums()
}


你可能感兴趣的:(iOS 设计模式-- 备忘录模式 - Memento)