Data persistence has always been a required lesson in iOS development. Plist file (property list) preference 3 NSKeyedArchiver (archive) 4 SQLite 3 5 CoreData

The main study today is the use of NSKeyedArchiver.

NSKeyedArchiver is a form of serialization in iOS and can be used to serialize objects that follow the NSCoding protocol. Fortunately, most of the Foundation and Cocoa Touch classes that support storing data follow the NSCoding protocol, so archiving is relatively easy to implement for most classes.

The following examples store Data of type Data, which follows the NSCoding protocol.

First, the setting of the storage path, the path had better be set as global variables

var filePath : String {
	let manager = FileManager.default
	let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
	return url.appendingPathComponent("objects")! .path }Copy the code

Two, storage, archiving

/ / stored in the first step to set up under the path of the value is stored data you wanted NSKeyedArchiver. ArchiveRootObject (value, toFile: filePath)Copy the code

Read from the path

// The format of the Data is the format of the Data you stored at that time. The format of the Data you stored is Data, and the format of the Model you stored is Model. Note that the value read is an optional value and needs to be used laterlet  value = NSKeyedUnarchiver.unarchiveObject(withFile: filePath)
Copy the code

4. Delete. So what do we do when we want to destroy this data

// Delete data, such as logging outlet exists = FileManager.default.fileExists(atPath: filePath)
		if exists {
			do{// Delete the data stored in the pathdo- Catchdo- catch my articles have the try FileManager. Default. RemoveItem (atPath: FilePath) // The next two lines are interface conversion and some data processing. You can do it according to your needs.true, completion: nil)
				self.delegate?.reloadLastViews()
			}catch let error as NSError {
				
				print("error: \(error.localizedDescription)")}}Copy the code

However, for data types that do not follow the NSCoding protocol, the protocol must be followed before archiving. For example, our Model implements two methods in Swift:

/** * NSCoding required initializer. * Fills the data from the passed decoder @objc Required init(coder aDecoder: NSCoder) {data = adecoder.decodeObject (forKey: "data") as? CurrentUserData
		isFail = aDecoder.decodeObject(forKey: "isFail") as? Bool
		isOk = aDecoder.decodeObject(forKey: "isOk") as? Bool} /** * NSCoding Required method. * Encodes mode properties into the decoder */ / encode(with aCoder: NSCoder) {ifdata ! = nil{ aCoder.encode(data,forKey: "data")}ifisFail ! = nil{ aCoder.encode(isFail,forKey: "isFail")}ifisOk ! = nil{ aCoder.encode(isOk,forKey: "isOk")}}Copy the code

Then follow the above four steps to do it