iOS开发中经常会需要一些常量,简单使用 plist 或者 NSUserDefaults
这里分享一下个人在项目中为了保证可读性以及方便而使用的常量类以及简单本地化方法
class ConstantsNumber {
static var clientUserId: Int64 {
set {
let id = Int(newValue)
setContentToDevice(id, key: "clientUserId", type: .userDefaults)
}
get {
guard getContentFromDevice("clientUserId", type: .userDefaults) != nil else {
return 0
}
return Int64(getContentFromDevice("clientUserId", type: .userDefaults) as! Int)
}
}
static var clientItemId: Int64 {
set {
let id = Int(newValue)
setContentToDevice(id, key: "clientItemId", type: .userDefaults)
}
get {
guard getContentFromDevice("clientItemId", type: .userDefaults) != nil else {
setContentToDevice(0, key: "clientItemId", type: .userDefaults)
return 0
}
return Int64(getContentFromDevice("clientItemId", type: .userDefaults) as! Int)
}
}
}
这样子使用常量就会非常容易,比如:
let id = Constants.clientItemId
配合下面两个 KyXu 写的的方法使用:
enum StoreType {
case userDefaults
case plist
}
func setContentToDevice (content:AnyObject, key:String, type:StoreType) {
if type == .userDefaults {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(content, forKey: key)
}else if type == .plist {
let pathPrefix = NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainsMask, true).first
let pathSuffix = "/" + key + ".plist"
if let path = pathPrefix?.stringByAppendingString(pathSuffix) {
NSKeyedArchiver.archiveRootObject(content, toFile: path)
}
}
}
func getContentFromDevice (key:String, type:StoreType) -> AnyObject? {
var returnObject :AnyObject?
if type == .userDefaults {
let defaults = NSUserDefaults.standardUserDefaults()
let content = defaults.objectForKey(key)
returnObject = content
}else if type == .plist {
let pathPrefix = NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainsMask, true).first
let pathSuffix = "/" + key + ".plist"
if let path = pathPrefix?.stringByAppendingString(pathSuffix) {
if let content = NSKeyedUnarchiver.unarchiveObjectWithFile(path) {
returnObject = content
}
}
}
return returnObject
}