2016-12-16 55 views
0

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

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

回答

1

提示:按Cmd + 4打开问题导航和Xcode中会告诉你更多的细节。

在斯威夫特3,编码功能发生了变化:

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

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

更改方法的签名,你应该罚款

0

在斯威夫特4还有另一种方式来编码/解码类。现在您只需遵守协议Codable。不再需要编写所有的编码和解码,并且它支持没有NSObject的类&枚举&结构。

final class Search: Codable { 

} 

欲了解更多信息,请阅读https://developer.apple.com/documentation/swift/codable

+0

这是不正确的。 NSCoding完全不会消失。你仍然需要它。你根本没有回答这个问题。 – matt

+0

你不需要NSCoding来解码/编码Swift 4.如果你阅读更多的信息链接,你会明白。这确实不是问题的答案,我提供了另一种解码/编码方式,它是更新的。 –

+0

你的第一句话是错误的。 NSCoding并没有完全改变。它一点都没有改变。而且你仍然会遇到需要实现'encode(with)'并且你没有解释做什么的问题。最后,你的回答与所提问题无关。它只是链接。这是一个错误的无益答案。 – matt