标签:
1 class func get_uuid() -> String{ 2 var userid = NSUserDefaults.standardUserDefaults().stringForKey("hangge") 3 if(userid != nil){ 4 return userid! 5 }else{ 6 var uuid_ref = CFUUIDCreate(nil) 7 var uuid_string_ref = CFUUIDCreateString(nil , uuid_ref) 8 var uuid:String = NSString(format: uuid_string_ref) 9 NSUserDefaults.standardUserDefaults().setObject(uuid, forKey: "hangge") 10 return uuid 11 } 12 }
1 var userDefault = NSUserDefaults.standardUserDefaults() 2 3 //AnyObject 4 userDefault.setObject("hangge.com", forKey: "Object") 5 var objectValue:AnyObject? = userDefault.objectForKey("Object") 6 7 //Int类型 8 userDefault.setInteger(12345, forKey: "Int") 9 var intValue = userDefault.integerForKey("Int") 10 11 //Float类型 12 userDefault.setFloat(3.2, forKey: "Float") 13 var floatValue = userDefault.floatForKey("Float") 14 15 //Double类型 16 userDefault.setDouble(5.2240, forKey: "Double") 17 var doubleValue = userDefault.doubleForKey("Double") 18 19 //Bool类型 20 userDefault.setBool(true, forKey: "Bool") 21 var boolValue = userDefault.boolForKey("Bool") 22 23 //NSURL类型 24 userDefault.setURL(NSURL(string:"http://hangge.com")!, forKey: "NSURL") 25 var urlValue = userDefault.URLForKey("NSURL") 26 27 //NSString类型 28 userDefault.setObject("hangge.com", forKey: "NSString") 29 var nsStringValue = userDefault.objectForKey("NSString") as! NSString 30 31 //NSNumber类型 32 var number:NSNumber = NSNumber(int:22) 33 userDefault.setObject(number, forKey: "NSNumber") 34 number = userDefault.objectForKey("NSNumber") as! NSNumber 35 36 //NSArray类型 37 var array:NSArray = NSArray(array: ["123","456"]) 38 userDefault.setObject(array, forKey: "NSArray") 39 40 //NSDictionaryy类型 41 var dictionary:NSDictionary = NSDictionary(dictionary: ["1":"hangge.com"]) 42 userDefault.setObject(dictionary, forKey: "NSDictionary") 43 dictionary = userDefault.objectForKey("NSDictionary") as! NSDictionary
1 var userDefault = NSUserDefaults.standardUserDefaults() 2 3 //UIImage对象存储 4 //将对象转换成NSData流 5 var image = UIImage(named: "apple.png") 6 var imageData:NSData = NSKeyedArchiver.archivedDataWithRootObject(image!) 7 //存储NSData对象 8 userDefault.setObject(imageData, forKey: "imageData") 9 10 //UIImage对象读取 11 //获取NSData 12 var objData:NSData = userDefault.objectForKey("imageData") as! NSData 13 //还原对象 14 var myImage = NSKeyedUnarchiver.unarchiveObjectWithData(objData) as! UIImage 15 println(myImage)
1 var userDefault = NSUserDefaults.standardUserDefaults() 2 3 //自定义对象存储 4 var model = UserInfo(name: "航歌", phone: "3525") 5 //实例对象转换成NSData 6 var modelData:NSData = NSKeyedArchiver.archivedDataWithRootObject(model) 7 //存储NSData对象 8 userDefault.setObject(modelData, forKey: "myModel") 9 10 //自定义对象读取 11 var myModelData = userDefault.objectForKey("myModel") as! NSData 12 var myModel = NSKeyedUnarchiver.unarchiveObjectWithData(myModelData) as! UserInfo
iOS开发——数据持久化&使用NSUserDefaults来进行本地数据存储
标签:
原文地址:http://www.cnblogs.com/iCocos/p/4671555.html