swift ios数据持久化UIImage
Posted
技术标签:
【中文标题】swift ios数据持久化UIImage【英文标题】:swift ios data persistence UIImage 【发布时间】:2015-09-26 03:10:51 【问题描述】:我创建了一个如下的类并想将数组:[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")
我在 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**
我 println(arrayOfObjectsUnarchived[0].icon) 发现它是 nil,无法获取我保存的原始图像,为什么?并使用以下方法保存是否足够?有人有像fileManger这样的其他方法吗?谢谢!!!!
让默认值 = NSUserDefaults.standardUserDefaults()
var arrayOfObjectsUnarchivedData = defaults.dataForKey("arrayOfObjectsKey")!
var arrayOfObjectsUnarchived = NSKeyedUnarchiver.unarchiveObjectWithData(arrayOfObjectsUnarchivedData) 一样! [成本类别]
【问题讨论】:
【参考方案1】:将UIImage
存储在NSUserDefaults
中不是一个好主意。
我建议将图像保存在文件系统中,您可以将它们的文件系统路径存储在您的模型中,然后可以驻留在NSUserDefaults
。
不过,如果你真的有兴趣,NSUserDefaults
中的图片是这样保存的:
写信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()
阅读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)
编辑:应 OP 请求
第 1 步: 编写一个方法,获取图像名称并返回文件系统中的图像路径。这里我将文件保存在Documents
目录中。
- (NSString *)imagePathForImage:(NSString *)iImageName
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:iImageName];
return imagePath;
第 2 步: 调用上述方法并将图片路径保存在您的costCategory
中。我不是为此编写代码。我希望你能把它连接起来。
第 3 步: 将图像保存在文件系统上。传递您从上述方法获得的图像和路径。
- (void)saveImage:(UIImage *)iImage toPath:(NSString *)iImagePath
NSData *imageData = UIImagePNGRepresentation(iImage);
[imageData writeToFile:iImagePath atomically:NO];
第 4 步:最后,当您从 NSUserDefaults
读取对象时,获取图像路径属性并调用以下方法来获取和渲染图像:
- (UIImage *)imageForPath:(NSString *)iImagePath
return [UIImage imageWithContentsOfFile:iImagePath];
【讨论】:
您真的给了我一个提示,将图像保存在文件系统中并将系统路径存储在我的模型中。我放弃了将 UIImage 保存在我的模型中的最初想法。但是你能给我一个简单的代码来演示如何保存它吗?我刚开始学习这部分,不熟悉。谢谢!!!! 看看我的编辑。希望对您有所帮助!以上是关于swift ios数据持久化UIImage的主要内容,如果未能解决你的问题,请参考以下文章
iOS:从 JSON 切换到 CoreData 以保持本地持久数据;这实用吗?数组内字典 数组内字典