如何在 NSUserDefaults 中存储自定义对象

hdk*_*mar 3 iphone objective-c nsuserdefaults ios

对于重复的问题,我深表歉意。我是 ios 新手。我想将自定义对象存储在用户默认值中。我正在使用 Objective-c 。

提前致谢

Vin*_*mar 5

首先,您创建自定义类,如下所示。

自定义对象.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject<NSCoding>

@property(strong,nonatomic)NSString *name;

@end 
Run Code Online (Sandbox Code Playgroud)

自定义对象.m

#import "CustomObject.h"

@implementation CustomObject



- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.name forKey:@"name"];

}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.name = [decoder decodeObjectForKey:@"name"];

    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

然后创建CustomObject类对象并存储在NSUserDefaults中

像这样存储你的对象

CustomObject *object =[CustomObject new];
object.name = @"test";

NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr  addObject:object];

NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arr];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:@"storeObject"];
[defaults synchronize];
Run Code Online (Sandbox Code Playgroud)

像这样从 NSUserDefaults 获取自定义对象

 NSData *storedEncodedObject = [defaults objectForKey:@"storeObject"];
        NSArray *arrStoreObject = [NSKeyedUnarchiver unarchiveObjectWithData:storedEncodedObject];
        for (int i=0; i<arrStoreObject.count; i++)
        {
            CustomObject *storedObject = [arrStoreObject objectAtIndex:i];
            NSLog(@"%@",storedObject.name);

        }
Run Code Online (Sandbox Code Playgroud)