iOS学习笔记——使用NSUserDefaults存储自定义数据

来源:互联网 发布:虚拟商品网站源码 编辑:程序博客网 时间:2024/06/05 02:07

NSUserDefaults的官方文档描述:

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. Applications record such preferences by assigning values to a set of parameters in a user’s defaults database. The parameters are referred to as defaults since they’re commonly used to determine an application’s default state at startup or the way it acts by default.

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSDataNSStringNSNumberNSDateNSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using stringForKey: will be immutable.

A defaults database is created automatically for each user. The NSUserDefaults class does not currently support per-host preferences. To do this, you must use the CFPreferences API (see Preferences Utilities Reference). However, NSUserDefaults correctly reads per-host preferences, so you can safely mix CFPreferences code with NSUserDefaults code.

If your application supports managed environments, you can use an NSUserDefaults object to determine which preferences are managed by an administrator for the benefit of the user. Managed environments correspond to computer labs or classrooms where an administrator or teacher may want to configure the systems in a particular way. In these situations, the teacher can establish a set of default preferences and force those preferences on users. If a preference is managed in this manner, applications should prevent users from editing that preference by disabling any appropriate controls.

The NSUserDefaults class is thread-safe.


要点翻译:
NSUserDefaults类可以存储NSDataNSStringNSNumberNSDateNSArray, or NSDictionary.类,如果需要存储自定义数据,需要将数据转换为NSData
NSUserDefaults返回的值是不可改变的,即便是你在存储的时候使用的是可变的值。例如你使用NSMutableString存储值"MyStringDefault",当你做使用stringForKey:方法获取的值,这个值仍然是不可变的。
NSUserDefaults是单例,是线程安全的.

那么如何使用NSUserDefaults存储自定义数据呢?
假设有一个学生类,存储学生的信息:(要将类中数据转换为NSData类,必须遵从NSCoding协议
#import <Foundation/Foundation.h>@interface Student : NSObject<NSCoding>@property (nonatomic,retain) NSString *name;@property (nonatomic,retain) NSString *ID;@property (nonatomic,retain) NSString *age;@end
#import "Student.h"@implementation Student- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.name forKey:@"name"];    [aCoder encodeObject:self.ID forKey:@"ID"];    [aCoder encodeObject:self.age forKey:@"age"];}- (id)initWithCoder:(NSCoder *)aDecoder{    if (self = [super init]) {        self.name = [aDecoder decodeObjectForKey:@"name"];        self.ID = [aDecoder decodeObjectForKey:@"ID"];        self.age = [aDecoder decodeObjectForKey:@"age"];    }    return self;}- (NSString *)description{    return [NSString stringWithFormat:@"name:%@, ID%@, age:%@",_name,_ID,_age];}@end

将自定义数据存入NSUserDefaults
//创建一个学生数组存储所有学生信息    NSMutableArray *studentMArray = [[NSMutableArray alloc] init];    //循环创建5个学生    for (int i = 0; i < 5; i++) {        Student *student = [[Student alloc] init];        student.name = [NSString stringWithFormat:@"student%d",i];        student.ID = [NSString stringWithFormat:@"000%d",i];        student.age = [NSString stringWithFormat:@"%d",arc4random() % 20 + 1];        //将学生对象转换为NSData数据流        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];        //将data存入学生数组中        [studentMArray addObject:data];    }    //NSUserdefaults介绍    /**     1.数据持久化工具,属性级别的保存数据的方式     2.原理:将通过NSUserdefaults的key-value形式将数据保存到一个.plist文件中,实现数据的持久化存储     3.NSUserdefaults:是通过单例调用方法     */        //获取唯一的对象    NSUserDefaults *stu = [NSUserDefaults standardUserDefaults];    //即使存的是NSMutableArray类型,用stringForKey取出时仍是不可变的    [stu setObject:studentMArray forKey:[NSString stringWithFormat:@"students"]];


NSUserDefaults取出学生数组中所有数据:
    //读取数组NSArray类型的数据    NSArray *studentArray = [[NSUserDefaults standardUserDefaults] arrayForKey:@"students"];    for(NSData *stuData in studentArray)    {        //将数组中NSData数据流通过NSKeyedUnarchiver转换为学生对象        Student *stu =[NSKeyedUnarchiver unarchiveObjectWithData:stuData];        NSLog(@"%@",stu);    }





0 0
原创粉丝点击