简体   繁体   English

清除 UserDefaults.standard.data 信息实际上并没有删除它?

[英]Clearing UserDefaults.standard.data information doesn't actually delete it?

I saved a UIImage to UserDefaults via.data with this code, where the key equals "petPhoto1":我使用此代码将 UIImage 保存到 UserDefaults via.data,其中键等于“petPhoto1”:

@IBAction func addPhotoButton(_ sender: Any) {
        
        let picker = UIImagePickerController()
        picker.allowsEditing = false
        picker.delegate = self
        picker.mediaTypes = ["public.image"]
        present(picker, animated: true)
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            image.storeInUserDefaults(for: "petPhoto\(activePet)")
            UserDefaults.standard.set("yes", forKey: "doesImageExist\(activePet)")
        }
        
        dismiss(animated: true, completion: nil)
    }

(unrelated stuff in between) (中间不相关的东西)

extension UIImage {
    func storeInUserDefaults(with compressionQuality: CGFloat = 0.8, for key:     String) {
    guard let data = self.jpegData(compressionQuality: compressionQuality) else { return }
    let encodedImage = try! PropertyListEncoder().encode(data)
    UserDefaults.standard.set(encodedImage, forKey: key)
    }
}

Now when I erase it like this:现在,当我像这样擦除它时:

UserDefaults.standard.set(nil, forKey: "petPhoto1")

I can still see that "Documents & Data" for my app under Settings is still full with the same size as the original image, indicating that it didn't actually delete it, even though it no longer displays when it gets loaded back from UserDefaults.我仍然可以看到我的应用程序在设置下的“文档和数据”仍然是完整的,大小与原始图像相同,这表明它实际上并没有删除它,即使它从 UserDefaults 加载回来时不再显示.

Can anyone figure out a way to fix this?谁能想办法解决这个问题? Thanks!谢谢!

By the way, in case it helps, here is other code related to this issue:顺便说一句,如果有帮助,这里是与此问题相关的其他代码:

The code I use in the ImageViewController that I display the image after saving it:我在保存图像后显示图像的 ImageViewController 中使用的代码:

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
        super.viewDidLoad()
        
        activePet = UserDefaults.standard.string(forKey: "activePet")! // activePet = 1 (confirmed with debugging with other, unrelated code
        
        imageView.image = try? UIImage.loadFromUserDefaults(with: "petPhoto\(activePet)")
        
    }

extension UIImage {
    static func loadFromUserDefaults(with key: String) throws -> UIImage? {
         let activePet = UserDefaults.standard.string(forKey: "activePet")!
         guard let data = UserDefaults.standard.data(forKey: "petPhoto\(activePet)") else {
             return nil
         }
         do {
             let decodedImageData = try PropertyListDecoder().decode(Data.self, from: data)
             return UIImage(data: decodedImageData)
         } catch let error {
             throw error
         }
     }
}

When you do this:当你这样做时:

UserDefaults.standard.set(nil, forKey: "petPhoto1")

The link between the key and the file saved will be removed synchronously.密钥和保存的文件之间的链接将被同步删除。 that means if you try to access the value for this key, it gives nil.这意味着如果您尝试访问此键的值,它会返回 nil。

But this image needs to be cleared from storage too, that will be happening asynchronously [we don't have completion handler API support from apple to get this information].但是这个图像也需要从存储中清除,这将异步发生[我们没有来自苹果的完成处理程序 API 支持来获取此信息]。

Apple Documentation for reference:苹果文档供参考:

At runtime, you use UserDefaults objects to read the defaults that your app uses from a user's defaults database.在运行时,您使用 UserDefaults 对象从用户的默认数据库中读取您的应用使用的默认值。 UserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. UserDefaults 缓存信息以避免每次需要默认值时都必须打开用户的默认数据库。 When you set a default value, it's changed synchronously within your process, and asynchronously to persistent storage and other processes.当您设置默认值时,它会在您的进程中同步更改,并异步更改为持久存储和其他进程。

What you can try:你可以尝试什么:

First approch第一种方法

Give some time for the file delete operation to get completed by OS.给一些时间让操作系统完成文件删除操作。 then try to access the image in the disk.然后尝试访问磁盘中的图像。

Second approch第二种方法

Try observing to the changes in the directory using GCD.尝试使用 GCD 观察目录中的更改。 Refer: https://stackoverflow.com/a/26878163/5215474参考: https://stackoverflow.com/a/26878163/5215474

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM