gpt4 book ai didi

Swift 对象数组到 plist 文件

转载 作者:行者123 更新时间:2023-11-30 13:44:33 24 4
gpt4 key购买 nike

我试图将对象的数组保存到 array.plist 但出现以下错误:

Thread 1: signal SIGABRT error

我的对象类如下所示:

class Note {
// MARK: Properties

var title: String
var photo: UIImage?
var text: String

// MARK: Initialization

init?(title: String, photo: UIImage?, text: String) {
// Initialize stored properties.
self.title = title
self.photo = photo
self.text = text

// Initialization should fail if there is no name or if the rating is negative.
if title.isEmpty{
return nil
}
}
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(title, forKey:"title")
aCoder.encodeObject(text, forKey:"text")
aCoder.encodeObject(photo, forKey:"photo")
}

init (coder aDecoder: NSCoder!) {
self.title = aDecoder.decodeObjectForKey("title") as! String
self.text = aDecoder.decodeObjectForKey("text") as! String
self.photo = aDecoder.decodeObjectForKey("photo") as! UIImage
}
}

在 Controller 中,我尝试使用 Notes 对象保存数组,如下所示:

notes = [Notes]()
notes.append(note)
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true)
let path: AnyObject = paths[0]
let arrPath = path.stringByAppendingString("/array.plist")

NSKeyedArchiver.archiveRootObject(notes, toFile: arrPath)

最佳答案

并非类中的所有属性都是可选的,但是当您从 plist 中检索它们时,您正在解包所有它们。这可能会导致您的代码崩溃。

例如,如果照片为 nil 并且您保存了该对象,则当您检索它时,您会将其展开 self.photo = aDecoder.decodeObjectForKey("photo") 为! UIImage,如果您没有在其中保存任何内容,它将崩溃。

尝试移除展开的包装并再次检查是否发生崩溃。即使这不是导致崩溃的原因,它也会在某个时候导致崩溃。

如果这不能解决您的问题,请粘贴完整的错误日志,以便更清楚地了解发生的情况。

关于Swift 对象数组到 plist 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35132548/

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