使用UserDefaults

时间:2015-09-05 00:42:21

标签: ios swift cocoa-touch nsuserdefaults

我有一个用户拍照的应用程序,一旦拍照,它应该保存到UserDefaults。我一直收到这个错误:

"cannot invoke 'setObject' with an argument list of type '(UIImage. type, forKey:[UIImage])'"

我在这里搜索了文档和帖子,但没有任何帮助。 这是我的代码。

let defaults = NSUserDefaults.standardUserDefaults()

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

    picker.dismissViewControllerAnimated(true, completion: nil)

    switch currentClothesSelection!{

        case "1":
            shirts.append(info[UIImagePickerControllerOriginalImage] as! UIImage)

            //this is where the error occurs
            defaults.setObject(UIImage.self, forKey: array1)

        case "2" :
            pants.append(info[UIImagePickerControllerOriginalImage] as! UIImage)
        case "3" :
            shorts.append(info[UIImagePickerControllerOriginalImage] as! UIImage)
        case "4" :
            jackets.append(info[UIImagePickerControllerOriginalImage] as! UIImage)
        case "5" :
            shoes.append(info[UIImagePickerControllerOriginalImage] as! UIImage)

        default:
         break
    }

2 个答案:

答案 0 :(得分:10)

编辑/更新:

Xcode 10.1•Swift 4.2.1或更高版本

在NSUserDefaults存储图像不是一个好主意,但如果你真的想这样做,你需要存储为NSData。

  

value参数只能是属性列表对象:NSData,   NSString,NSNumber,NSDate,NSArray或NSDictionary。对于NSArray和NSDictionary对象,其内容必须是属性列表对象

我建议在Documents文件夹中将其本地保存到磁盘。如果您真的想将其保存到NSUserDefaults,我建议您只使用小图片并自行承担风险:)您可以按照以下步骤操作:

extension UserDefaults {
    func set(image: UIImage?, quality: CGFloat = 0.5, forKey defaultName: String) {
        guard let image = image else {
            set(nil, forKey: defaultName)
            return
        }
        set(image.jpegData(compressionQuality: quality), forKey: defaultName)
    }
    func image(forKey defaultName:String) -> UIImage? {
        guard
            let data = data(forKey: defaultName),
            let image = UIImage(data: data)
        else  { return nil }
        return image
    }
    func set(images value: [UIImage]?, forKey defaultName: String) throws {
        guard let value = value else {
            removeObject(forKey: defaultName)
            return
        }
        try set(NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false), forKey: defaultName)
    }
    func images(forKey defaultName: String) throws -> [UIImage] {
        guard let data = data(forKey: defaultName) else { return [] }

        let object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
        return object as? [UIImage] ?? []
    }
}

测试:

let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!))!
UserDefaults.standard.set(image: image, forKey: "imageKey")
if let loadedImage = UserDefaults.standard.image(forKey: "imageKey") {
    print(loadedImage.size)  // "(719.0, 808.0)"
}

let images = [image, image]
try? UserDefaults.standard.set(images: images, forKey: "imagesKey")
if let loadedImages = try? UserDefaults.standard.images(forKey: "imagesKey") {
    print(loadedImages.count)  // 2
}

答案 1 :(得分:2)

在NSUserDefaults中保存blob数据将对您的应用程序造成巨大的性能损失。您有两种选择:

  1. 将缓存文件夹中的图像另存为文件,并使用NSUserDefaults存储其路径
  2. 使用CoreData,SQLite或Realm数据库存储图像。数据的数据结构将决定哪一个更合适。