您的位置:首页 > Web前端

【iOS开发-75】iOS数据存储的三种简单方式:plist、preference以及用NSCoding存储对象

2014-11-13 12:53 756 查看
实际开发中,存储数据主要是用SQLite。而在练习中,我们主要用如下三种存储方式。

(1)利用plist存储简单地NSString、NSArray、NSDictionary等。



(2)利用preference存储,和上面的类似,存储的是简单的数据,本质上还是一个plist文件。



(3)利用NSCoding存储对象这些复杂的数据,本质上是一个data文件,需要被存储的类遵守NSCoding协议并实现init和encode方法。



代码如下:

——在ViewController.m中

- (void)viewDidLoad {
//我们保存的数据主要是存在Documents中,会被iTunes备份
//tmp中数据可能会被随时清除
//Library中的Caches保存的时缓存,不会被清除,但也不会被iTunes备份
//Library中的Preference保存的时偏好设置,会被iTunes备份
//1、保存到plist文件中
NSString *homePath=NSHomeDirectory();
NSString *docPath=[homePath stringByAppendingPathComponent:@"Documents"];
NSString *filePath=[docPath stringByAppendingPathComponent:@"data2plist.plist"];
NSArray *array=@[@"aaa",@10,@"hello"];
[array writeToFile:filePath atomically:YES];
//1、读取plist文件
NSArray *arrayOut=[NSArray arrayWithContentsOfFile:filePath];
for (int i=0; i<arrayOut.count; i++) {
NSLog(@"%@",arrayOut[i]);
}

//2、保存到preference中,相比plist,就是少了路径,因为这个路径是紫铜自动判断的
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:@"hello" forKey:@"1"];
[defaults setBool:YES forKey:@"yue"];
[defaults setInteger:10 forKey:@"age"];
//立即同步(好习惯)
[defaults synchronize];
//2、读取数据
NSString *str1=[defaults objectForKey:@"1"];
BOOL bool1=[defaults boolForKey:@"yue"];
int integer1=[defaults integerForKey:@"age"];
NSLog(@"%@,%d,%i",str1,bool1,integer1);
//以上需要注意的是,preference数据存放的地方和xcode5的模拟器不同

//3、用NSCoding保存对象
WPPerson *p1=[[WPPerson alloc]init];
p1.name=@"andy";
p1.age=30;
NSString *filePath2=[docPath stringByAppendingPathComponent:@"data2data.data"];
[NSKeyedArchiver archiveRootObject:p1 toFile:filePath2];
//3、读取数据
WPPerson *p2=[NSKeyedUnarchiver unarchiveObjectWithFile:filePath2];
NSLog(@"%@,%i",p2.name,p2.age);

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

——为了第三个例子创建了一个WPPerson类,继承自NSObject的简单地类。
WPPerson.h中:

#import <Foundation/Foundation.h>

@interface WPPerson : NSObject<NSCoding>
@property(nonatomic,copy) NSString *name;
@property(nonatomic,assign) int age;
@end

WPPerson.m中:
#import "WPPerson.h"

@implementation WPPerson

-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInt:_age forKey:@"age"];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
if (self=[super init]) {
_name=[aDecoder decodeObjectForKey:@"name"];
_age=[aDecoder decodeIntForKey:@"age"];
}
return self;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐