【发布时间】:2016-03-16 01:29:42
【问题描述】:
非常简单的问题 - 如何在 Swift 中临时存储图像、字符串和双精度值?
我的应用程序从服务器获取 ID,使用此 ID 应用程序可以从服务器请求下载图像,然后通过另一个请求可以获取 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(如我的示例)是存储数据的可能方式,我不确定这是否是一个好主意,就我而言
【问题讨论】:
-
是的,可能,虽然我不确定该使用什么。我读过 NSUserDefaults 不能很好地存储超过 100Kb 的数据?
-
我发现了两种将照片保存到文档或照片库的替代方法,它们都不是我想要的,因为照片将在应用程序运行时使用,并且通常在应用程序关闭后不会再次使用。
标签: ios swift class save nsobject