[英]swift ios data persistence UIImage
I create a class as following and want to save array: [costCategory] to disk, 我按如下方式创建一个类,并希望将数组:[costCategory]保存到磁盘,
class costCategory : NSObject, NSCoding {
var name : String
var defaultValue : Int
var thisMonthsEstimate : Int
var sumOfThisMonthsActuals : Int
var riskFactor : Float
var monthlyAverage : Float
var icon: UIImage!
init (name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float, icon: UIImage) {
self.name = name
self.defaultValue = defaultValue
self.thisMonthsEstimate = thisMonthsEstimate
self.sumOfThisMonthsActuals = sumOfThisMonthsActuals
self.riskFactor = riskFactor
self.monthlyAverage = monthlyAverage
self.icon = icon
}
// MARK: NSCoding
required init(coder decoder: NSCoder) {
//Error here "missing argument for parameter name in call
self.name = decoder.decodeObjectForKey("name") as! String
self.defaultValue = decoder.decodeIntegerForKey("defaultValue")
self.thisMonthsEstimate = decoder.decodeIntegerForKey("thisMonthsEstimate")
self.sumOfThisMonthsActuals = decoder.decodeIntegerForKey("sumOfThisMonthsActuals")
self.riskFactor = decoder.decodeFloatForKey("riskFactor")
self.monthlyAverage = decoder.decodeFloatForKey("monthlyAverage")
self.icon = decoder.decodeObjectForKey("icon") as! UIImage!
super.init()
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.name, forKey: "name")
coder.encodeInt(Int32(self.defaultValue), forKey: "defaultValue")
coder.encodeInt(Int32(self.thisMonthsEstimate), forKey: "thisMonthsEstimate")
coder.encodeInt(Int32(self.sumOfThisMonthsActuals), forKey: "sumOfThisMonthsActuals")
coder.encodeFloat(self.riskFactor, forKey: "riskFactor")
coder.encodeFloat(self.monthlyAverage, forKey: "monthlyAverage")
coder.encodeObject(self.icon, forKey: "icon")
}
} }
I save data in viewController as following: 我将数据保存在viewController中,如下所示:
class ViewController: UIViewController { 类ViewController:UIViewController {
@IBOutlet weak var photo: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let defaults = NSUserDefaults.standardUserDefaults()
let arrayOfObjectsKey = "arrayOfObjectsKey"
var arrayOfObjects = [costCategory]()
arrayOfObjects.append(costCategory(name: "Mark", defaultValue: 50, thisMonthsEstimate: 60, sumOfThisMonthsActuals: 70, riskFactor:80, monthlyAverage:90, icon: UIImage(named:"Mark.JPG")!))
arrayOfObjects.append(costCategory(name: "Mary", defaultValue: 50, thisMonthsEstimate: 60, sumOfThisMonthsActuals: 70, riskFactor:80, monthlyAverage:90, icon: UIImage(named:"Mary.JPG")!))
var arrayOfObjectsData = NSKeyedArchiver.archivedDataWithRootObject(arrayOfObjects)
var arrayOfObjectsUnarchivedData = defaults.dataForKey("arrayOfObjectsKey")!
var arrayOfObjectsUnarchived = NSKeyedUnarchiver.unarchiveObjectWithData(arrayOfObjectsUnarchivedData) as! [costCategory]
**println(arrayOfObjectsUnarchived[0].icon)**
**photo.image = arrayOfObjectsUnarchived[0].icon**
}
} }
I println(arrayOfObjectsUnarchived[0].icon) find it is nil, cannot get the original image that I save, Why? 我println(arrayOfObjectsUnarchived [0] .icon)发现它为零,无法获取我保存的原始图像,为什么? And use following method to save is good enough?
并使用以下方法保存就足够好了吗? Anyone have other mathod like fileManger?
有人有其他方法像fileManger吗? Thanks!!!!
谢谢!!!!
let defaults = NSUserDefaults.standardUserDefaults() 让默认值= NSUserDefaults.standardUserDefaults()
var arrayOfObjectsUnarchivedData = defaults.dataForKey("arrayOfObjectsKey")! var arrayOfObjectsUnarchivedData = defaults.dataForKey(“ arrayOfObjectsKey”)!
var arrayOfObjectsUnarchived = NSKeyedUnarchiver.unarchiveObjectWithData(arrayOfObjectsUnarchivedData) as! var arrayOfObjectsUnarchived = NSKeyedUnarchiver.unarchiveObjectWithData(arrayOfObjectsUnarchivedData)一样! [costCategory]
[costCategory]
Storing UIImage
in NSUserDefaults
is not a good idea. 在
NSUserDefaults
存储UIImage
不是一个好主意。
I would advise to save images in file system and you can store their file system path in your model which can then reside in NSUserDefaults
. 我建议将图像保存在文件系统中,然后将其文件系统路径存储在模型中,然后将其驻留在
NSUserDefaults
。
However, if you really interested , this is how images are saved in NSUserDefaults
: 但是,如果您真的感兴趣,可以使用以下方法将图像保存在
NSUserDefaults
:
Writing UIImage
: 编写
UIImage
:
let imageData = UIImageJPEGRepresentation(image, 1)
let relativePath = "image_\(NSDate.timeIntervalSinceReferenceDate()).jpg"
let path = self.documentsPathForFileName(relativePath)
imageData.writeToFile(path, atomically: true)
NSUserDefaults.standardUserDefaults().setObject(relativePath, forKey: "path")
NSUserDefaults.standardUserDefaults().synchronize()
Reading UIImage
: 读取
UIImage
:
let possibleOldImagePath = NSUserDefaults.standardUserDefaults().objectForKey("path") as String?
if let oldImagePath = possibleOldImagePath {
let oldFullPath = self.documentsPathForFileName(oldImagePath)
let oldImageData = NSData(contentsOfFile: oldFullPath)
// here is your saved image:
let oldImage = UIImage(data: oldImageData)
}
EDIT: On OP request 编辑:在OP请求
Step 1: Write a method that takes image name and return you image path in file system. 步骤1:编写一个使用映像名称并在文件系统中返回映像路径的方法。 Here I am saving files in
Documents
directory. 在这里,我将文件保存在
Documents
目录中。
- (NSString *)imagePathForImage:(NSString *)iImageName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:iImageName];
return imagePath;
}
Step 2: Call above method and save image path in your costCategory
. 第2步:调用上述方法,并将图像路径保存在
costCategory
。 I am not writing code for this. 我没有为此编写代码。 I hope you can connect that.
希望您能联系上。
Step 3: Save Image on file system. 步骤3:将映像保存在文件系统上。 Pass your image and path you got from above method.
传递您从上述方法获得的图像和路径。
- (void)saveImage:(UIImage *)iImage toPath:(NSString *)iImagePath {
NSData *imageData = UIImagePNGRepresentation(iImage);
[imageData writeToFile:iImagePath atomically:NO];
}
Step 4: Finally, when you read your object from NSUserDefaults
, fetch the image path property and call below method to get & render the image: 步骤4:最后,当您从
NSUserDefaults
读取对象时,获取图像路径属性并调用下面的方法来获取并呈现图像:
- (UIImage *)imageForPath:(NSString *)iImagePath {
return [UIImage imageWithContentsOfFile:iImagePath];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.