iOS存储的三种方式

时间:2022-04-27 08:05:02

iOS中存储的3中方式:

1.NSUserDefaults

注意存储基本对象类型是没有问题的,但是要存储自定义对象,则要将对象内所有的属性(或是需要存储的属性)序列化,实现NSCoding协议序列化。

存:
[[NSUserDefaults standardUserDefaults] setValue:@"yellow" forKey:@"color"]; [[NSUserDefaults standardUserDefaults] synchronize];
取:
NSString *color = [[NSUserDefaults standardUserDefaults] objectForKey:@"color"];

对于存储的是自定义的对象:(示例Contact的序列化)

#import <Foundation/Foundation.h>

@interface Contact : NSObject <NSCoding>

@property (nonatomic,retain) NSString *name;
@property (nonatomic,retain) NSString *phoneNumber; + (id)contactsWithName:(NSString *)aName phoneNumber:(NSString *)aPhoneNumber; @end
#import "Contact.h"

#define kNameKey  @"NameKey"
#define kPhoneNumberKey @"PhoneNumberKey" @implementation Contact - (id)initWithName:(NSString *)aName phoneNumber:(NSString *)aPhoneNumber
{
if (self = [super init])
{
self.name = aName;
self.phoneNumber = aPhoneNumber;
} return self;
} //初始化配套的便利方法 ,静态方法中的self 不代表当前类的对象,代表当前类本身
+ (id)contactsWithName:(NSString *)aName phoneNumber:(NSString *)aPhoneNumber
{
return [[[self alloc] initWithName:aName phoneNumber:aPhoneNumber] autorelease]; } //对象序列化的两个协议方法 //对象序列化的方法,把对象的所有属性编码到本地
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:kNameKey];
[aCoder encodeObject:_phoneNumber forKey:kPhoneNumberKey];
} //对象反序列化的方法
- (id)initWithCoder:(NSCoder *)aDecoder
{
if(self = [super init])
{
self.name = [aDecoder decodeObjectForKey:kNameKey];
self.phoneNumber = [aDecoder decodeObjectForKey:kPhoneNumberKey];
} return self;
}

2.沙盒

- (void)viewDidLoad
{
[super viewDidLoad]; NSMutableDictionary *savedDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath]]; //如果第一次进入,从userdefault中取不到数据,手动创建一个字典
if (!savedDic)
{
self.dic = [NSMutableDictionary dictionaryWithCapacity:];
}
else
{
self.dic = savedDic;
}
//注册一个即将进入后台的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveData) name:UIApplicationWillResignActiveNotification object:nil]; } //返回文件的路径
- (NSString *)dataFilePath
{
//沙盒
//获得沙盒下面Documents文件夹的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"paths %@",paths);
NSString *path = [paths objectAtIndex:];
//在documents 路径下,追加一个文件路径
NSString *filePath = [path stringByAppendingPathComponent:@"select.plist"]; return filePath;
} - (void)saveData
{
//字典当中存储的value 必须是 array dictionary Boolean data date nsnumber nsstring
//把一个字典写到文件中,实际上是按照plist 的格式去组织数据的
[_dic writeToFile:[self dataFilePath] atomically:YES];
NSMutableDictionary *savedDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath]];
}

3.sqlite