gpt4 book ai didi

ios - xcode NSInvalidUnarchiveOperationException ,当尝试取消存档文件时

转载 作者:可可西里 更新时间:2023-11-01 06:17:46 25 4
gpt4 key购买 nike

这是 xcode 抛出的错误:

Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeInt64ForKey:]: value for key (rating) is not an integer number'

这是创建 Meal 对象的类的一部分:

//MARK: Properties

var rating: Int
var name: String
var photo: UIImage?

//MARK: Path

static let DocumentDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains:.UserDomainMask).first!

static let ArchivelUrl = DocumentDirectory.URLByAppendingPathComponent("meals")

//MARK: NSCoding

func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: propertyKey.nameKey)
aCoder.encodeObject(photo, forKey: propertyKey.photoKey)
aCoder.encodeInteger(rating, forKey: propertyKey.ratingKey)

}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(propertyKey.nameKey) as! String
let photo = aDecoder.decodeObjectForKey(propertyKey.photoKey) as? UIImage
let rating = aDecoder.decodeIntegerForKey(propertyKey.ratingKey)
//must call to designate initiallizer
self.init(name: name,photo: photo,rating: rating)
}

这是存档器和解档器:

//MARK: NSCoding

func saveMeal(){
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile:Meal.ArchivelUrl.path!)

if !isSuccessfulSave {
print("Failed to save")
}
else{
print("saved")
}
}

func loadMeal() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchivelUrl.path!) as [Meal] }

我在苹果网站上遵循了这个教程:[ https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html

示例项目有效。我试图将我的代码复制到他们的项目文件中,它也有效。所以我认为这里的设置有所不同!

最佳答案

我通过替换以下代码解决的问题:

let rating = aDecoder.decodeIntegerForKey(propertyKey.ratingKey)
to
let rating = aDecoder.decodeObjectForKey(propertyKey.ratingKey) as! Int

我猜你之前已经将评级编译并保存为对象而不是整数,所以当你将对象解码为整数时,它会告诉你对象不是整数(因为编译器不知道对象类型是什么)

或者你可以打印你的 Meal.ArchivelUrl.path! 并删除现有的 meal.text,然后删除模拟器中的应用程序,然后编译你的代码再次张贴在这里。我认为那会很好(至少对我来说很好)。

关于ios - xcode NSInvalidUnarchiveOperationException ,当尝试取消存档文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31086593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com