Project address: github.com/zzjzz9266a/…

lead

The company’s project did not cache the homepage data before, so the user experience is not good, so now we need to store the homepage data locally.

implementation

Consider using NSKeyedArchiver first, but with this you need to follow the NSCoding protocol and type each attribute in the model. But our project uses ObjectMapper to parse JSON, following the Mapple protocol, we have already set the mapping relationship for every attribute in the model, do we need to write it again? This is repeating the wheel

If you think about it later, json files are nothing more than arrays and dictionaries, except that their types are determined by root and child nodes, and NSArray and NSDictionary have writeToFile methods. Just convert the model to the corresponding NSArray and NSDictionary types.

The installation

Published to CocoaPods:

pod 'ObjectMapperCacheManager'
Copy the code

Method of use

The key is a unique identifier when storing data on the device, similar to how UserDefaults is used.

UserDefaults.standard.setValue(["name": "James"."age": 16], forKey: "User")
Copy the code

The only difference from UserDefaults is the path to the sandbox:

  • UserDefaultsIs stored inHome/Library/Preference/
  • ObjectMapperCacheManagerIs stored inHome/Library/Caches

1. The storekey-value(native dictionary or array) type

The data format can be a dictionary or an array:

let dict: [String: Any] = ["name": "James"."age": 16]
CacheManager.setCache(json: dict, for: "Json")

let dictArray = [[String: Any]] = [dict]
CacheManager.setCache(json: dictArray, for: "JsonArray")
Copy the code

2. To obtainkey-valuetype

// The type must be explicitly declared
if let dict: [String: Any] = CacheManager.cacheJson(for: "Json") as? [String: Any] {//print(dict)
}

if let array: [[String: Any]] = CacheManager.cacheJson(for: "JsonArray") as? [String: Any] {//print(array)
}
Copy the code

3. StoreObjectMapperType or an array of objects

The type of the stored object must comply with the Mapple protocol in ObjectMapper:

let user: User = User(a)CacheManager.setCache(object: user, for: "Object")

let userList = [user]
CacheManager.setCache(array: userList, for: "ObjectArray")
Copy the code

4. To obtainObjectMapperType or an array of objects

// The type must be explicitly declared
if let user: User = CacheManager.cache(for: "Object") {
  //Do Something
}

if let array: [User] = CacheManager.cacheArray(for: "ObjectArray") {
  //Do Something
}

Copy the code