我创建了一个自定义对象。我已使用NSCoder将自定义对象保存到nsuserdefaults。我向对象添加了一个NSArray,我试图将另一个自定义对象附加到此数组。尝试这样做时,我不断收到此错误:“NSArray类型的值没有成员附加”。如何防止此错误,并能够使用此自定义对象数组将自定义对象保存到nsuserdefaults。
这是自定义类:
class Person: NSObject, NSCoding {
var name: String!
var age: Int!
var image: UIImage!
var arr: NSArray!
required convenience init(coder decoder: NSCoder) {
self.init()
self.name = decoder.decodeObjectForKey("name") as! String
self.age = decoder.decodeObjectForKey("age") as! Int
self.image = decoder.decodeObjectForKey("image") as! UIImage
self.image = decoder.decodeObjectForKey("image") as! UIImage }
convenience init(name: String, age: Int, img: UIImage, array: NSArray) {
self.init()
self.name = name
self.age = age
self.image = img
self.arr = array
}
func encodeWithCoder(coder: NSCoder) {
if let name = name { coder.encodeObject(name, forKey: "name") }
if let age = age { coder.encodeObject(age, forKey: "age") }
if let img = image {coder.encodeObject(image, forKey: "image") }
if let arr = arr {coder.encodeObject(arr, forKey: "array") }
}
}
这是保存和附加代码:
import UIKit
import Foundation
var newPerson = Person()
var oldPerson = Person(name: "John", age: 100, img: newPerson.image, array: [1, 2, 3, 4])
class ViewController: UIViewController {
@IBOutlet var image: UIImageView!
@IBOutlet var textField: UITextField!
@IBAction func Save(sender: AnyObject) {
newPerson.name = textField.text
newPerson.age = 10
newPerson.image = UIImage(named: "afghan_flag.jpg")
newPerson.arr.append(oldPerson)
let personData = NSKeyedArchiver.archivedDataWithRootObject(newPerson)
NSUserDefaults().setObject(personData, forKey: "personData")
}
@IBAction func Load(sender: AnyObject) {
if let loadedData = NSUserDefaults().dataForKey("personData") {
if let loadedPerson = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? Person {
print(loadedPerson.name)
}
}strong text
}
}
答案 0 :(得分:0)
如果你像这样定义它,你可以拥有一个Person数组
var arrayPerson : [Person] = []
然后你可以使用arrrayPerson.append(newPerson)