我正在尝试保存我在swift中连接在一起的声音数组,然后加载它们。但是,所有数据都会正确保存,但是当我尝试加载它时,数据所拥有的所有属性都不再存在,但它仍然将数据计为现有数据,而不保存任何属性。我很困惑为什么会发生这种情况
struct saveSound{
static func save(newSound: mergedSound = mergedSound()){
if newSound.soundName == "" || newSound.soundUrl == "" { print("no new data") ; return}
var sounds = loadSounds.getSounds()
sounds.append(newSound)
let archive = NSKeyedArchiver.archivedData(withRootObject: sounds)
for soun in sounds{
print(soun.soundName," - saved")
}
UserDefaults.standard.set(archive, forKey: "SavedSounds")
}
}
struct loadSounds {
static func getSounds() -> [mergedSound]{
var sounds = [mergedSound]()
var data = Data()
if UserDefaults.standard.object(forKey: "SavedSounds") as? Data != nil {
print("data exists")
data = UserDefaults.standard.object(forKey: "SavedSounds") as! Data
sounds = NSKeyedUnarchiver.unarchiveObject(with: data) as! [mergedSound]
for souns in sounds{
print(souns.soundName,sounds.count, " - loaded")
}
}
return sounds
}
}
答案 0 :(得分:1)
您确定您的数据实际已保存吗?您是否查看过首选项PLIST文件进行验证?您的日志语句无法实际验证此假设。
此外,您的Sound
班级NSCoding
是否合规?您是否实施协议来归档/取消归档每个属性?如果不是(如果您声明合规性但不处理类的自定义属性),则永远不会写入(或读取)它们,并且您的未归档实例将具有默认值。