非常简单的问题 - 如何在 Swift 中临时存储图像、字符串和 double 值?
我的应用程序从服务器获取 ID,使用此 ID 应用程序可以从服务器请求下载图像,然后通过另一个请求可以获得 String 和 Double。 然后应用程序必须显示带有相应 String 和 Double 的图像。 一旦应用程序被终止并在应用程序启动后再次下载,应删除所有下载的数据。
使用自定义类是个好主意吗?
例如,客户类别:
class UserInformation: NSObject {
var string: String
var double: Double
var image: String
init(string: String, double: Double, image: String) {
self.string = string
self.double = double
self.image = image
}
}
然后保存和访问数据:
var info = [UserInformation]()
func save() {
//Alamofire functions to download image and string, double values goes here
var newImage = //Downloaded image from server
var newString = //Downloaded String from server
var newDouble = //Downloaded Double from server
//Save image
let imageName = NSUUID().UUIDString
let imagePath = getDocumentsDirectory().stringByAppendingPathComponent(imageName)
if let jpegData = UIImageJPEGRepresentation(newImage, 80) {
jpegData.writeToFile(imagePath, atomically: true)
}
let userInfo = UserInformation(string: newString, double: newDouble, image: imageName)
info.append(userInfo)
}
func load() {
//For ex. I am using [0], although in my app
//it would be for _ in _ loop to access all existing values
let info = UserInformation[0]
string.text = info.string
double.double = info.double
let path = getDocumentsDirectory().stringByAppendingPathComponent(info.image)
imageView.image = UIImage(contentsOfFile: path)
}
func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
编辑 我意识到使用 NSUserData(如我的示例)是存储数据的可能方式,我不确定这是否是个好主意,就我而言
最佳答案
你想要什么被命名为“持久数据”。您可以通过多种方法实现这一目标: 1.可以使用第三方库 2. 将数据保存在 plist 文件或 CoreData 或 UserDefaults 中。您可以创建一个包含任何您想要的内容的字典,但 UI 对象除外,例如 UIImage。您可以在 NSData 中转换 UIImage,然后保存 NSData。
最简单的方法是保存在 NSUserDefaults 中。那里有一个如何做到这一点的例子:Save images in NSUserDefaults?
关于ios - 如何在 Swift 中临时存储图像和字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34201446/