符合NSCoding

时间:2016-12-16 22:46:48

标签: swift nsuserdefaults nscoding

我不能为我的生活弄清楚为什么我得到这个类不符合NSCoding协议的错误。也许另一组眼睛会有所帮助。我试图添加注释以明确每个func正在做什么。

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
}
}

2 个答案:

答案 0 :(得分:2)

提示:按Cmd + 4打开问题导航器,Xcode会告诉您更多详细信息。

在Swift 3中,编码功能已更改:

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

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

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

答案 1 :(得分:0)

在Swift 4中,还有另一种编码/解码类的方法。现在,您只需遵守协议Codable即可。不再需要编写所有的编码和解码,它支持没有NSObject&的类。 enums&结构

final class Search: Codable {

}

有关详情,请参阅https://developer.apple.com/documentation/swift/codable