CodexBloom - AI-Powered Q&A Platform

macOS 13.2 - NSKeyedUnarchiver Crashes with 'Invalid data' when Loading Custom Object

👀 Views: 1 💬 Answers: 1 📅 Created: 2025-06-06
swift macos nscoding debugging

I'm experiencing a crash in my macOS app (targeting macOS 13.2) when trying to load a custom object using `NSKeyedUnarchiver`. The object is saved in a file but when I attempt to unarchive it, I'm getting an error: `Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Invalid data.'`. Here's my custom class that conforms to `NSSecureCoding`: ```swift class MyCustomObject: NSObject, NSSecureCoding { static var supportsSecureCoding: Bool = true var name: String var value: Int init(name: String, value: Int) { self.name = name self.value = value } required init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(of: NSString.self, forKey: "name") as String? else { return nil } self.name = name self.value = aDecoder.decodeInteger(forKey: "value") } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(value, forKey: "value") } } ``` I save the object like this: ```swift let myObject = MyCustomObject(name: "Test", value: 42) let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("myObject.dat") NSKeyedArchiver.archiveRootObject(myObject, toFile: fileURL.path) ``` Then I try to load it with: ```swift if let loadedObject = NSKeyedUnarchiver.unarchiveObject(withFile: fileURL.path) as? MyCustomObject { print("Loaded object: \(loadedObject.name), \(loadedObject.value)") } ``` This worked fine previously, but now it seems to be failing and I'm unsure why. I've verified that the file exists at the specified path. I also tried clearing the app's cache and reinstalling it, but the issue persists. Is there something specific to macOS 13.2 that affects `NSKeyedUnarchiver` or `NSSecureCoding` that I might be missing? Any insights or suggestions would be greatly appreciated!