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

[英]how can store custom objects in NSUserDefaults


I apologize for duplicate Question . I am new in ios . I want to store custom objects in userdefaults. I am using objective-c .

我为重复的问题道歉。我是ios的新手。我想在userdefaults中存储自定义对象。我用的是objective-c。

Thanks in advance

谢谢提前

2 个解决方案

#1


3  

First you create custom class Like below.

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

CustomObject.h

CustomObject.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject<NSCoding>

@property(strong,nonatomic)NSString *name;

@end 

CustomObject.m

CustomObject.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;
}

Then create CustomObject class object and store in NSUserDefaults

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

Stored your object like this

像这样存储对象

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];

get custom object from NSUserDefaults like this

从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);

        }

#2


0  

In Swift 3

在斯威夫特3

        // set a value for key
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: #YOUR OBJECT#)
        UserDefaults.standard.set(encodedData, forKey: #YOUR KEY#)

        // retrieving a value for a key
        if let data = UserDefaults.standard.data(forKey:  #YOUR KEY#),
            let obj = NSKeyedUnarchiver.unarchiveObject(with: data) as? #YOUR OBJECT# {
        } else {
            print("There is an issue")
        }
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/04/07/720351cd40a1a395aedfe3e298a4494e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告