gpt4 book ai didi

swift - 符合 NSCoding

转载 作者:行者123 更新时间:2023-11-28 12:34:46 27 4
gpt4 key购买 nike

我一辈子都弄不明白为什么我会收到此类不符合 NSCoding 协议(protocol)的错误。也许另一双眼睛会有所帮助。我试图添加注释以明确每个函数在做什么。

import Foundation
import UIKit

class Search: NSObject, NSCoding {

// Global Variables
var articlePicture: UIImage!
var articleTitle: String

// MARK: Public Init
init(articlePicture: UIImage, articleTitle: String) {
self.articlePicture = articlePicture
self.articleTitle = articleTitle
}

// Required NSCoding Protocol
required convenience init?(coder decoder: NSCoder) {
guard let articlePicture = decoder.decodeObject(forKey: "articlePicture") as? UIImage,
let articleTitle = decoder.decodeObject(forKey: "articleTitle") as? String
else { return nil }

self.init(
articlePicture: articlePicture,
articleTitle: articleTitle
)
}

// Required NSCoding Protocal
func encodeWithCoder(coder: NSCoder) {
coder.encode(self.articlePicture, forKey: "articlePicture")
coder.encode(self.articleTitle, forKey: "articleTitle")
}

// Initialize [Search]
static var searches = [Search]()

static func getSearches() -> [Search]{
return searches
}

static func setSearch(search: Search){
searches.append(search)
}

// NSUserDefaults Searches Array funcs
static func saveSearches(){
let searchData = NSKeyedArchiver.archivedData(withRootObject: searches)
UserDefaults.standard.set(searchData, forKey: "searches")
}

static func loadSearches() -> [Search]{
let searchData = UserDefaults.standard.object(forKey: "searches") as? NSData

if let searchData = searchData {
searches = (NSKeyedUnarchiver.unarchiveObject(with: searchData as Data) as? [Search])!
return searches
}
return searches
}
}

最佳答案

提示:按 Cmd + 4 打开 Issue Navigator,Xcode 会告诉你更多细节。

在 Swift 3 中,编码函数发生了变化:

func encodeWithCoder(coder: NSCoder) {
// Swift 2 and older
}

func encode(with coder: NSCoder) {
// Swift 3
}

改变方法的签名,你应该没问题

关于swift - 符合 NSCoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41193498/

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