尝试使用 Swift 在 NSUserDefaults 中保存图像时出错 [英] Error when trying to save image in NSUserDefaults using Swift

查看:52
本文介绍了尝试使用 Swift 在 NSUserDefaults 中保存图像时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 NSUserDefaults 中保存图像时,应用程序因此错误而崩溃.

When i try to save an image in NSUserDefaults, the app crashed with this error.

为什么?是否可以使用 NSUserDefaults 保存图像?如果没有,那我该如何保存图片?

Why? Is it possible to save an image with NSUserDefaults? If not, then how do I save the image?

图片...

代码...

var image1:UIImage = image1

var save1: NSUserDefaults = NSUserDefaults.standardUserDefaults()

save1.setObject(Info.Image1, forKey: "Image1")       

save1.synchronize()

日志错误...

libc++abi.dylib:以 NSException 类型的未捕获异常终止(lldb)

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

推荐答案

NSUserDefaults 不仅仅是一辆大卡车,你可以把任何你想要的东西扔到上面.这是一系列只有特定类型的管子.

NSUserDefaults isn't just a big truck you can throw anything you want onto. It's a series of tubes which only specific types.

您可以保存到 NSUserDefaults 的内容:

What you can save to NSUserDefaults:

  • NSData
  • NSString
  • NSNumber
  • NSDate
  • NSArray
  • NSDictionary

如果您尝试将其他任何内容保存到 NSUserDefaults,您通常需要将其存档到一个 NSData 对象并存储它(请记住,您将有以便稍后在您需要时将其解压缩).

If you're trying to save anything else to NSUserDefaults, you typically need to archive it to an NSData object and store it (keeping in mind you'll have to unarchive it later when you need it back).

有两种方法可以将 UIImage 对象转换为数据.有一些函数可以创建图像的 PNG 表示或图像的 JPEG 表示.

There are two ways to turn a UIImage object into data. There are functions for creating a PNG representation of the image or a JPEG representation of the image.

对于 PNG:

let imageData = UIImagePNGRepresentation(yourImage)

对于 JPEG:

let imageData = UIImageJPEGRepresentation(yourImage, 1.0)

其中第二个参数是表示压缩质量的 CGFloat0.0 是最低质量,1.0 是最高质量.请记住,如果您使用 JPEG,每次压缩和解压缩时,如果您使用的是 1.0 以外的任何东西,随着时间的推移,您将降低质量.PNG 是无损的,因此您不会降低图像质量.

where the second argument is a CGFloat representing the compression quality, with 0.0 being the lowest quality and 1.0 being the highest quality. Keep in mind that if you use JPEG, each time you compress and uncompress, if you're using anything but 1.0, you're going to degrade the quality over time. PNG is lossless so you won't degrade the image.

要从数据对象中取回图像,UIImage 有一个 init 方法来执行此操作:

To get the image back out of the data object, there's an init method for UIImage to do this:

let yourImage = UIImage(data:imageData)

无论您如何将 UIImage 对象转换为数据,此方法都将起作用.

This method will work no matter how you converted the UIImage object to data.

在较新版本的 Swift 中,这些函数已被重命名和重组,现在被调用为:

In newer versions of Swift, the functions have been renamed, and reorganized, and are now invoked as:

对于 PNG:

let imageData = yourImage.pngData()

对于 JPEG:

let imageData = yourImage.jpegData(compressionQuality: 1.0)

尽管 Xcode 会为您自动更正旧版本

Although Xcode will autocorrect the old versions for you

这篇关于尝试使用 Swift 在 NSUserDefaults 中保存图像时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆