214

我以为我知道是什么导致了这个错误,但我似乎无法弄清楚我做错了什么。

这是我收到的完整错误消息:

尝试设置非属性列表对象 (
   “<BC_Person: 0x8f3c140>”
) 作为关键 personDataArray 的 NSUserDefaults 值

我有一个Person我认为符合NSCoding协议的类,我的 person 类中有这两种方法:

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.personsName forKey:@"BCPersonsName"];
    [coder encodeObject:self.personsBills forKey:@"BCPersonsBillsArray"];
}

- (id)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        self.personsName = [coder decodeObjectForKey:@"BCPersonsName"];
        self.personsBills = [coder decodeObjectForKey:@"BCPersonsBillsArray"];
    }
    return self;
}

在应用程序的某个时刻,设置了NSStringin BC_PersonClass,并且我有一个DataSave类,我认为它正在处理我的BC_PersonClass. 这是我在DataSave课堂上使用的代码:

- (void)savePersonArrayData:(BC_Person *)personObject
{
   // NSLog(@"name of the person %@", personObject.personsName);

    [mutableDataArray addObject:personObject];

    // set the temp array to the mutableData array
    tempMuteArray = [NSMutableArray arrayWithArray:mutableDataArray];

    // save the person object as nsData
    NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];

    // first add the person object to the mutable array
    [tempMuteArray addObject:personEncodedObject];

    // NSLog(@"Objects in the array %lu", (unsigned long)mutableDataArray.count);

    // now we set that data array to the mutable array for saving
    dataArray = [[NSArray alloc] initWithArray:mutableDataArray];
    //dataArray = [NSArray arrayWithArray:mutableDataArray];

    // save the object to NS User Defaults
    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
    [userData setObject:dataArray forKey:@"personDataArray"];
    [userData synchronize];
}

我希望这是足够的代码让您了解我正在尝试做什么。我再次知道我的问题在于我如何在我的 BC_Person 类中编码我的属性,我似乎无法弄清楚我做错了什么。

谢谢您的帮助!

4

12 回答 12

284

您发布的代码尝试将一组自定义对象保存到NSUserDefaults. 你不能那样做。实施这些NSCoding方法没有帮助。您只能存储NSArray, NSDictionary, NSString, NSData,NSNumberNSDatein之类的内容NSUserDefaults

您需要将对象转换为NSData(就像您在某些代码中所做的那样)并将其存储NSDataNSUserDefaults. 如果需要,NSArray您甚至可以存储一个。NSData

当您读回数组时,您需要取消归档NSData以取回您的BC_Person对象。

也许你想要这个:

- (void)savePersonArrayData:(BC_Person *)personObject {
    [mutableDataArray addObject:personObject];

    NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
    for (BC_Person *personObject in mutableDataArray) { 
        NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
        [archiveArray addObject:personEncodedObject];
    }

    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
    [userData setObject:archiveArray forKey:@"personDataArray"];
}
于 2013-11-01T04:13:56.177 回答
67

对我来说,自己遍历数组并将对象编码为 NSData 似乎相当浪费。您的错误BC_Person is a non-property-list object是告诉您框架不知道如何序列化您的 person 对象。

因此,所需要做的就是确保您的 person 对象符合 NSCoding,然后您可以简单地将您的自定义对象数组转换为 NSData 并将其存储为默认值。这是一个游乐场:

编辑:Xcode 7 上的写入NSUserDefaults中断,因此操场将存档到数据并返回并打印输出。包括 UserDefaults 步骤,以防它在以后修复

//: Playground - noun: a place where people can play

import Foundation

class Person: NSObject, NSCoding {
    let surname: String
    let firstname: String

    required init(firstname:String, surname:String) {
        self.firstname = firstname
        self.surname = surname
        super.init()
    }

    //MARK: - NSCoding -
    required init(coder aDecoder: NSCoder) {
        surname = aDecoder.decodeObjectForKey("surname") as! String
        firstname = aDecoder.decodeObjectForKey("firstname") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(firstname, forKey: "firstname")
        aCoder.encodeObject(surname, forKey: "surname")
    }
}

//: ### Now lets define a function to convert our array to NSData

func archivePeople(people:[Person]) -> NSData {
    let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(people as NSArray)
    return archivedObject
}

//: ### Create some people

let people = [Person(firstname: "johnny", surname:"appleseed"),Person(firstname: "peter", surname: "mill")]

//: ### Archive our people to NSData

let peopleData = archivePeople(people)

if let unarchivedPeople = NSKeyedUnarchiver.unarchiveObjectWithData(peopleData) as? [Person] {
    for person in unarchivedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Failed to unarchive people")
}

//: ### Lets try use NSUserDefaults
let UserDefaultsPeopleKey = "peoplekey"
func savePeople(people:[Person]) {
    let archivedObject = archivePeople(people)
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(archivedObject, forKey: UserDefaultsPeopleKey)
    defaults.synchronize()
}

func retrievePeople() -> [Person]? {
    if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsPeopleKey) as? NSData {
        return NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [Person]
    }
    return nil
}

if let retrievedPeople = retrievePeople() {
    for person in retrievedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Writing to UserDefaults is still broken in playgrounds")
}

瞧,您已将一组自定义对象存储到 NSUserDefaults

于 2015-01-29T15:30:18.387 回答
52

保存:

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourObject];
[currentDefaults setObject:data forKey:@"yourKeyName"];

要得到:

NSData *data = [currentDefaults objectForKey:@"yourKeyName"];
yourObjectType * token = [NSKeyedUnarchiver unarchiveObjectWithData:data];

对于删除

[currentDefaults removeObjectForKey:@"yourKeyName"];
于 2016-02-08T19:04:35.237 回答
35

斯威夫特 3 解决方案

简单的实用程序类

class ArchiveUtil {

    private static let PeopleKey = "PeopleKey"

    private static func archivePeople(people : [Human]) -> NSData {

        return NSKeyedArchiver.archivedData(withRootObject: people as NSArray) as NSData
    }

    static func loadPeople() -> [Human]? {

        if let unarchivedObject = UserDefaults.standard.object(forKey: PeopleKey) as? Data {

            return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Human]
        }

        return nil
    }

    static func savePeople(people : [Human]?) {

        let archivedObject = archivePeople(people: people!)
        UserDefaults.standard.set(archivedObject, forKey: PeopleKey)
        UserDefaults.standard.synchronize()
    }

}

模型类

class Human: NSObject, NSCoding {

    var name:String?
    var age:Int?

    required init(n:String, a:Int) {

        name = n
        age = a
    }


    required init(coder aDecoder: NSCoder) {

        name = aDecoder.decodeObject(forKey: "name") as? String
        age = aDecoder.decodeInteger(forKey: "age")
    }


    public func encode(with aCoder: NSCoder) {

        aCoder.encode(name, forKey: "name")
        aCoder.encode(age, forKey: "age")

    }
}

如何打电话

var people = [Human]()

people.append(Human(n: "Sazzad", a: 21))
people.append(Human(n: "Hissain", a: 22))
people.append(Human(n: "Khan", a: 23))

ArchiveUtil.savePeople(people: people)

let others = ArchiveUtil.loadPeople()

for human in others! {

    print("name = \(human.name!), age = \(human.age!)")
}
于 2017-02-16T04:26:40.000 回答
14

斯威夫特- 4 Xcode 9.1

试试这个代码

你不能在 NSUserDefault 中存储 mapper,你只能存储 NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary。

let myData = NSKeyedArchiver.archivedData(withRootObject: myJson)
UserDefaults.standard.set(myData, forKey: "userJson")

let recovedUserJsonData = UserDefaults.standard.object(forKey: "userJson")
let recovedUserJson = NSKeyedUnarchiver.unarchiveObject(with: recovedUserJsonData)
于 2018-05-23T05:47:23.863 回答
11

首先,rmaddy 的回答(上面)是正确的:实施NSCoding没有帮助。但是,您需要实现NSCoding使用NSKeyedArchiver和所有这些,所以这只是多一步...转换通过NSData.

示例方法

- (NSUserDefaults *) defaults {
    return [NSUserDefaults standardUserDefaults];
}

- (void) persistObj:(id)value forKey:(NSString *)key {
    [self.defaults setObject:value  forKey:key];
    [self.defaults synchronize];
}

- (void) persistObjAsData:(id)encodableObject forKey:(NSString *)key {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:encodableObject];
    [self persistObj:data forKey:key];
}    

- (id) objectFromDataWithKey:(NSString*)key {
    NSData *data = [self.defaults objectForKey:key];
    return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

所以你可以把你的NSCoding对象包装在一个NSArrayNSDictionary任何东西中......

于 2015-08-20T19:16:55.623 回答
11

斯威夫特_@propertyWrapper

Codable将对象保存到UserDefault

@propertyWrapper
    struct UserDefault<T: Codable> {
        let key: String
        let defaultValue: T

        init(_ key: String, defaultValue: T) {
            self.key = key
            self.defaultValue = defaultValue
        }

        var wrappedValue: T {
            get {

                if let data = UserDefaults.standard.object(forKey: key) as? Data,
                    let user = try? JSONDecoder().decode(T.self, from: data) {
                    return user

                }

                return  defaultValue
            }
            set {
                if let encoded = try? JSONEncoder().encode(newValue) {
                    UserDefaults.standard.set(encoded, forKey: key)
                }
            }
        }
    }




enum GlobalSettings {

    @UserDefault("user", defaultValue: User(name:"",pass:"")) static var user: User
}

示例用户模型确认可编码

struct User:Codable {
    let name:String
    let pass:String
}

如何使用它

//Set value 
 GlobalSettings.user = User(name: "Ahmed", pass: "Ahmed")

//GetValue
print(GlobalSettings.user)
于 2020-04-09T22:56:30.687 回答
8

我在尝试将字典保存到NSUserDefaults. 事实证明它不会保存,因为它包含NSNull值。所以我只是将字典复制到一个可变字典中删除了空值然后保存到NSUserDefaults

NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary_trying_to_save];
[dictionary removeObjectForKey:@"NullKey"];
[[NSUserDefaults standardUserDefaults] setObject:dictionary forKey:@"key"];

在这种情况下,我知道哪些键可能是NSNull值。

于 2016-04-21T11:13:21.403 回答
5

https://developer.apple.com/reference/foundation/userdefaults

默认对象必须是一个属性列表——即,NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary 的实例(或集合的实例组合)。

如果要存储任何其他类型的对象,通常应该将其归档以创建 NSData 的实例。有关更多详细信息,请参阅首选项和设置编程指南。

于 2017-06-02T12:40:48.913 回答
5

Swift 5:可以使用Codable协议代替NSKeyedArchiever

struct User: Codable {
    let id: String
    let mail: String
    let fullName: String
}

Pref结构是围绕 UserDefaults 标准对象的自定义包装器。

struct Pref {
    static let keyUser = "Pref.User"
    static var user: User? {
        get {
            if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
                do {
                    return try JSONDecoder().decode(User.self, from: data)
                } catch {
                    print("Error while decoding user data")
                }
            }
            return nil
        }
        set {
            if let newValue = newValue {
                do {
                    let data = try JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: keyUser)
                } catch {
                    print("Error while encoding user data")
                }
            } else {
                UserDefaults.standard.removeObject(forKey: keyUser)
            }
        }
    }
}

所以你可以这样使用它:

Pref.user?.name = "John"

if let user = Pref.user {...
于 2019-06-22T15:53:55.053 回答
4

Swift 5非常简单的方法

//MARK:- First you need to encoded your arr or what ever object you want to save in UserDefaults
//in my case i want to save Picture (NMutableArray) in the User Defaults in
//in this array some objects are UIImage & Strings

//first i have to encoded the NMutableArray 
let encodedData = NSKeyedArchiver.archivedData(withRootObject: yourArrayName)
//MARK:- Array save in UserDefaults
defaults.set(encodedData, forKey: "YourKeyName")

//MARK:- When you want to retreive data from UserDefaults
let decoded  = defaults.object(forKey: "YourKeyName") as! Data
yourArrayName = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! NSMutableArray

//MARK: Enjoy this arrry "yourArrayName"
于 2019-06-17T06:14:23.553 回答
1

我遇到了这个问题,最终发现这是因为我试图NSNumber用作字典键,而属性列表只允许字符串作为键。的文档setObject:forKey:没有提到这个限制,但是它链接到的About Property Lists页面确实:

按照惯例,表 2-1 中列出的每个 Cocoa 和 Core Foundation 对象都称为属性列表对象。从概念上讲,您可以将“属性列表”视为所有这些类的抽象超类。如果您从某个方法或函数接收到一个属性列表对象,您就知道它必须是这些类型之一的实例,但您可能不知道先验是哪种类型。如果属性列表对象是容器(即数组或字典),则其中包含的所有对象也必须是属性列表对象。如果数组或字典包含不是属性列表对象的对象,则无法使用各种属性列表方法和函数保存和恢复数据层次结构。尽管 NSDictionary 和 CFDictionary 对象允许它们的键是任何类型的对象,如果键不是字符串对象,则集合不是属性列表对象。

(强调我的)

于 2020-12-04T16:48:17.157 回答