Swift在设置异常中保存cutom类:' NSInvalidArgumentException',原因:' *** -length仅为抽象类定义

时间:2015-05-12 09:17:49

标签: swift settings nscoding

您好我尝试使用NSUserDefaults存储自定义对象。我使用了这篇有用的帖子Saving custom SWIFT class with NSCoding to UserDefaults

但是当我试用时,我得到以下异常

  

2015-05-12 11:05:14.994 KirchnerTime [4424:75095] *因未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' * - 长度仅为抽象类定义。定义 - [项目长度]!'

import Foundation

@objc(Project)
public class ProjectJobEntity: NSData, NSCoding  
{
private let _barCode: String
private var _projectNumber: String
private var _projectDescription: String
private var _jobDescription: String

public var BarCode: String
{
    get { return self._barCode }
}

public var ProjectNumber: String
{
    get { return self._projectNumber }
    set { self._projectNumber = newValue }
}

public var ProjectDescription: String
{
    get { return self._projectDescription }
    set { self._projectDescription = newValue }
}

public var JobDescription: String
{
    get { return self._jobDescription }
    set { self._jobDescription = newValue }
}

public init(barCode: String, projectNumber: String, projectDescription: String, jobDescription: String)
{
    self._barCode = barCode
    self._projectNumber = projectNumber
    self._projectDescription = projectDescription
    self._jobDescription = jobDescription

    super.init()
}


public init(barCode: String)
{
    self._barCode = barCode
    self._projectNumber = ""
    self._projectDescription = ""
    self._jobDescription = ""

    super.init()
}

override public func encodeWithCoder(aCoder: NSCoder)
{
    aCoder.encodeObject(self._barCode, forKey: "barCode")
    aCoder.encodeObject(self._projectNumber, forKey: "projectNumber")
    aCoder.encodeObject(self._projectDescription, forKey: "projectDescription")
    aCoder.encodeObject(self._jobDescription, forKey: "jobDescription")
}

required public init(coder aDecoder: NSCoder)
{
    self._barCode = aDecoder.decodeObjectForKey("barCode") as! String
    self._projectNumber = aDecoder.decodeObjectForKey("projectNumber") as! String
    self._projectDescription = aDecoder.decodeObjectForKey("projectDescription") as! String
    self._jobDescription = aDecoder.decodeObjectForKey("jobDescription") as! String

    super.init(coder: aDecoder)
}

这是应该存储的对象。

 public func saveSettings()
{
    let settings = NSUserDefaults.standardUserDefaults()
    settings.setValue(self._cardNumber, forKeyPath: cardNumberKey)

    settings.setObject(NSKeyedArchiver.archivedDataWithRootObject(ProjectJobEntity(barCode: "Test")), forKey: "Project")
}

这就是我尝试的方式。

1 个答案:

答案 0 :(得分:0)

我有同样的例外。

我使用NSObject作为父类。

在代码

下使用
svn