以代码实例总结iOS应用开发中数据的存储方式
程序员文章站
2023-01-01 19:30:28
ios数据存储包括以下几种存储机制:
属性列表
对象归档
sqlite3
coredata
appsettings
普通文件存储...
ios数据存储包括以下几种存储机制:
- 属性列表
- 对象归档
- sqlite3
- coredata
- appsettings
- 普通文件存储
1、属性列表
复制代码 代码如下:
//
// persistence1viewcontroller.h
// persistence1
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import <uikit/uikit.h>
#define kfilename @"data.plist"
@interface persistence1viewcontroller : uiviewcontroller {
uitextfield *filed1;
uitextfield *field2;
uitextfield *field3;
uitextfield *field4;
}
@property (nonatomic, retain) iboutlet uitextfield *field1;
@property (nonatomic, retain) iboutlet uitextfield *field2;
@property (nonatomic, retain) iboutlet uitextfield *field3;
@property (nonatomic, retain) iboutlet uitextfield *field4;
- (nsstring *)datafilepath;
- (void)applicationwillresignactive:(nsnotification *)notification;
@end
复制代码 代码如下:
//
// persistence1viewcontroller.m
// persistence1
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import "persistence1viewcontroller.h"
@implementation persistence1viewcontroller
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//数据文件的完整路径
- (nsstring *)datafilepath {
//检索documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);
//每个应用程序只有一个documents目录
nsstring *documentsdirectory = [paths objectatindex:0];
//创建文件名
return [documentsdirectory stringbyappendingpathcomponent:kfilename];
}
//应用程序退出时,将数据保存到属性列表文件
- (void)applicationwillresignactive:(nsnotification *)notification {
nsmutablearray *array = [[nsmutablearray alloc] init];
[array addobject: field1.text];
[array addobject: field2.text];
[array addobject: field3.text];
[array addobject: field4.text];
[array writetofile:[self datafilepath] atomically:yes];
[array release];
}
/*
// the designated initializer. override to perform setup that is required before the view is loaded.
- (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil {
self = [super initwithnibname:nibnameornil bundle:nibbundleornil];
if (self) {
// custom initialization
}
return self;
}
*/
/*
// implement loadview to create a view hierarchy programmatically, without using a nib.
- (void)loadview {
}
*/
// implement viewdidload to do additional setup after loading the view, typically from a nib.
- (void)viewdidload {
[super viewdidload];
nsstring *filepath = [self datafilepath];
//检查数据文件是否存在
if([[nsfilemanager defaultmanager] fileexistsatpath:filepath]) {
nsarray *array = [[nsarray alloc] initwithcontentsoffile:filepath];
field1.text = [array objectatindex:0];
field2.text = [array objectatindex:1];
field3.text = [array objectatindex:2];
field4.text = [array objectatindex:3];
[array release];
}
uiapplication *app = [uiapplication sharedapplication];
[[nsnotificationcenter defaultcenter] addobserver:self
selector:@selector(applicationwillresignactive:)
name:uiapplicationwillresignactivenotification
object:app];
[super viewdidload];
}
/*
// override to allow orientations other than the default portrait orientation.
- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation {
// return yes for supported orientations
return (interfaceorientation == uiinterfaceorientationportrait);
}
*/
- (void)didreceivememorywarning {
// releases the view if it doesn't have a superview.
[super didreceivememorywarning];
// release any cached data, images, etc that aren't in use.
}
- (void)viewdidunload {
self.field1 = nil;
self.field2 = nil;
self.field3 = nil;
self.field4 = nil;
[super viewdidunload];
}
- (void)dealloc {
[field1 release];
[field2 release];
[field3 release];
[field4 release];
[super dealloc];
}
@end
2、对象归档
复制代码 代码如下:
//
// fourlines.h
// persistence2
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import <foundation/foundation.h>
@interface fourlines : nsobject <nscoding, nscopying> {
nsstring *field1;
nsstring *field2;
nsstring *field3;
nsstring *field4;
}
@property (nonatomic, retain) nsstring *field1;
@property (nonatomic, retain) nsstring *field2;
@property (nonatomic, retain) nsstring *field3;
@property (nonatomic, retain) nsstring *field4;
@end
复制代码 代码如下:
//
// fourlines.m
// persistence2
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import "fourlines.h"
#define kfield1key @"field1"
#define kfield2key @"field2"
#define kfield3key @"field3"
#define kfield4key @"field4"
@implementation fourlines
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
#pragma mark nscoding
- (void)encodewithcoder:(nscoder *)acoder {
[acoder encodeobject:field1 forkey:kfield1key];
[acoder encodeobject:field2 forkey:kfield2key];
[acoder encodeobject:field3 forkey:kfield3key];
[acoder encodeobject:field4 forkey:kfield4key];
}
-(id) initwithcoder:(nscoder *)adecoder {
if(self = [super init]) {
field1 = [[adecoder decodeobjectforkey:kfield1key] retain];
field2 = [[adecoder decodeobjectforkey:kfield2key] retain];
field3 = [[adecoder decodeobjectforkey:kfield3key] retain];
field4 = [[adecoder decodeobjectforkey:kfield4key] retain];
}
return self;
}
#pragma mark -
#pragma mark nscopying
- (id) copywithzone:(nszone *)zone {
fourlines *copy = [[[self class] allocwithzone: zone] init];
copy.field1 = [[self.field1 copywithzone: zone] autorelease];
copy.field2 = [[self.field2 copywithzone: zone] autorelease];
copy.field3 = [[self.field3 copywithzone: zone] autorelease];
copy.field4 = [[self.field4 copywithzone: zone] autorelease];
return copy;
}
@end
复制代码 代码如下:
//
// persistence2viewcontroller.h
// persistence2
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import <uikit/uikit.h>
#define kfilename @"archive"
#define kdatakey @"data"
@interface persistence2viewcontroller : uiviewcontroller {
uitextfield *filed1;
uitextfield *field2;
uitextfield *field3;
uitextfield *field4;
}
@property (nonatomic, retain) iboutlet uitextfield *field1;
@property (nonatomic, retain) iboutlet uitextfield *field2;
@property (nonatomic, retain) iboutlet uitextfield *field3;
@property (nonatomic, retain) iboutlet uitextfield *field4;
- (nsstring *)datafilepath;
- (void)applicationwillresignactive:(nsnotification *)notification;
@end
复制代码 代码如下:
//
// persistence2viewcontroller.m
// persistence2
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import "persistence2viewcontroller.h"
#import "fourlines.h"
@implementation persistence2viewcontroller
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//数据文件的完整路径
- (nsstring *)datafilepath {
//检索documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);
//每个应用程序只有一个documents目录
nsstring *documentsdirectory = [paths objectatindex:0];
//创建文件名
return [documentsdirectory stringbyappendingpathcomponent:kfilename];
}
//应用程序退出时,将数据保存到属性列表文件
- (void)applicationwillresignactive:(nsnotification *)notification {
fourlines *fourlines = [[fourlines alloc] init];
fourlines.field1 = field1.text;
fourlines.field2 = field2.text;
fourlines.field3 = field3.text;
fourlines.field4 = field4.text;
nsmutabledata *data = [[nsmutabledata alloc] init];//用于存储编码的数据
nskeyedarchiver *archiver = [[nskeyedarchiver alloc] initforwritingwithmutabledata:data];
[archiver encodeobject:fourlines forkey:kdatakey];
[archiver finishencoding];
[data writetofile:[self datafilepath] atomically:yes];
[fourlines release];
[archiver release];
[data release];
}
/*
// the designated initializer. override to perform setup that is required before the view is loaded.
- (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil {
self = [super initwithnibname:nibnameornil bundle:nibbundleornil];
if (self) {
// custom initialization
}
return self;
}
*/
/*
// implement loadview to create a view hierarchy programmatically, without using a nib.
- (void)loadview {
}
*/
// implement viewdidload to do additional setup after loading the view, typically from a nib.
- (void)viewdidload {
[super viewdidload];
nsstring *filepath = [self datafilepath];
//检查数据文件是否存在
if([[nsfilemanager defaultmanager] fileexistsatpath:filepath]) {
//从文件获取用于解码的数据
nsdata *data = [[nsmutabledata alloc] initwithcontentsoffile:[self datafilepath]];
nskeyedunarchiver *unarchiver = [[nskeyedunarchiver alloc] initforreadingwithdata:data];
fourlines *fourlines = [unarchiver decodeobjectforkey:kdatakey];
[unarchiver finishdecoding];
field1.text = fourlines.field1;
field2.text = fourlines.field2;
field3.text = fourlines.field3;
field4.text = fourlines.field4;
[unarchiver release];
[data release];
}
uiapplication *app = [uiapplication sharedapplication];
[[nsnotificationcenter defaultcenter] addobserver:self
selector:@selector(applicationwillresignactive:)
name:uiapplicationwillresignactivenotification
object:app];
[super viewdidload];
}
/*
// override to allow orientations other than the default portrait orientation.
- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation {
// return yes for supported orientations
return (interfaceorientation == uiinterfaceorientationportrait);
}
*/
- (void)didreceivememorywarning {
// releases the view if it doesn't have a superview.
[super didreceivememorywarning];
// release any cached data, images, etc that aren't in use.
}
- (void)viewdidunload {
self.field1 = nil;
self.field2 = nil;
self.field3 = nil;
self.field4 = nil;
[super viewdidunload];
}
- (void)dealloc {
[field1 release];
[field2 release];
[field3 release];
[field4 release];
[super dealloc];
}
@end
3、sqlite
复制代码 代码如下:
//
// persistence3viewcontroller.h
// persistence3
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import <uikit/uikit.h>
#define kfilename @"data.sqlite3"
@interface persistence3viewcontroller : uiviewcontroller {
uitextfield *filed1;
uitextfield *field2;
uitextfield *field3;
uitextfield *field4;
}
@property (nonatomic, retain) iboutlet uitextfield *field1;
@property (nonatomic, retain) iboutlet uitextfield *field2;
@property (nonatomic, retain) iboutlet uitextfield *field3;
@property (nonatomic, retain) iboutlet uitextfield *field4;
- (nsstring *)datafilepath;
- (void)applicationwillresignactive:(nsnotification *)notification;
@end
复制代码 代码如下:
//
// persistence3viewcontroller.m
// persistence3
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import "persistence3viewcontroller.h"
#import <sqlite3.h>
@implementation persistence3viewcontroller
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//数据文件的完整路径
- (nsstring *)datafilepath {
//检索documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);
//每个应用程序只有一个documents目录
nsstring *documentsdirectory = [paths objectatindex:0];
//创建文件名
return [documentsdirectory stringbyappendingpathcomponent:kfilename];
}
//应用程序退出时,将数据保存到属性列表文件
- (void)applicationwillresignactive:(nsnotification *)notification {
sqlite3 *database;
if(sqlite3_open([[self datafilepath] utf8string], &database) != sqlite_ok) {
sqlite3_close(database);
nsassert(0, @"failed to open database");
}
for(int i = 1; i <= 4; i++) {
nsstring *fieldname = [[nsstring alloc] initwithformat:@"field%d", i];
uitextfield *field = [self valueforkey:fieldname];
[fieldname release];
char *update = "insert or replace into fields (row, field_data) values (?, ?);";
sqlite3_stmt *stmt;
//将sql语句编译为sqlite内部一个结构体(sqlite3_stmt),类似java jdbc的preparedstatement预编译
if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == sqlite_ok) {
//在bind参数的时候,参数列表的index从1开始,而取出数据的时候,列的index是从0开始
sqlite3_bind_int(stmt, 1, i);
sqlite3_bind_text(stmt, 2, [field.text utf8string], -1, null);
} else {
nsassert(0, @"error:failed to prepare statemen");
}
//执行sql文,获取结果
int result = sqlite3_step(stmt);
if(result != sqlite_done) {
nsassert1(0, @"error updating table: %d", result);
}
//释放stmt占用的内存(sqlite3_prepare_v2()分配的)
sqlite3_finalize(stmt);
}
sqlite3_close(database);
}
/*
// the designated initializer. override to perform setup that is required before the view is loaded.
- (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil {
self = [super initwithnibname:nibnameornil bundle:nibbundleornil];
if (self) {
// custom initialization
}
return self;
}
*/
/*
// implement loadview to create a view hierarchy programmatically, without using a nib.
- (void)loadview {
}
*/
// implement viewdidload to do additional setup after loading the view, typically from a nib.
- (void)viewdidload {
[super viewdidload];
nsstring *filepath = [self datafilepath];
//检查数据文件是否存在
if([[nsfilemanager defaultmanager] fileexistsatpath:filepath]) {
//打开数据库
sqlite3 *database;
if(sqlite3_open([filepath utf8string], &database) != sqlite_ok) {
sqlite3_close(database);
nsassert(0, @"failed to open database");
}
//创建表
char *errormsg;
nsstring *createsql =
@"create table if not exists fields (row integer primary key, field_data text);";
if(sqlite3_exec(database, [createsql utf8string], null, null, &errormsg) != sqlite_ok) {
sqlite3_close(database);
nsassert(0, @"error creating table: %s", errormsg);
}
//查询
nsstring *query = @"select row, field_data from fields order by row";
sqlite3_stmt *statement;
//设置nbyte可以加速操作
if(sqlite3_prepare_v2(database, [query utf8string], -1, &statement, nil) == sqlite_ok) {
while (sqlite3_step(statement) == sqlite_row) {//返回每一行
int row = sqlite3_column_int(statement, 0);
char *rowdata = (char *)sqlite3_column_text(statement, 1);
nsstring *fieldname = [[nsstring alloc] initwithformat:@"field%d", row];
nsstring *fieldvalue = [[nsstring alloc] initwithutf8string:rowdata];
uitextfield *field = [self valueforkey:fieldname];
field.text = fieldvalue;
[fieldname release];
[fieldvalue release];
}
//释放statement占用的内存(sqlite3_prepare()分配的)
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
uiapplication *app = [uiapplication sharedapplication];
[[nsnotificationcenter defaultcenter] addobserver:self
selector:@selector(applicationwillresignactive:)
name:uiapplicationwillresignactivenotification
object:app];
[super viewdidload];
}
/*
// override to allow orientations other than the default portrait orientation.
- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation {
// return yes for supported orientations
return (interfaceorientation == uiinterfaceorientationportrait);
}
*/
- (void)didreceivememorywarning {
// releases the view if it doesn't have a superview.
[super didreceivememorywarning];
// release any cached data, images, etc that aren't in use.
}
- (void)viewdidunload {
self.field1 = nil;
self.field2 = nil;
self.field3 = nil;
self.field4 = nil;
[super viewdidunload];
}
- (void)dealloc {
[field1 release];
[field2 release];
[field3 release];
[field4 release];
[super dealloc];
}
@end
4、core data
复制代码 代码如下:
//
// persistenceviewcontroller.h
// persistence4
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import <uikit/uikit.h>
@interface persistenceviewcontroller : uiviewcontroller {
uitextfield *filed1;
uitextfield *field2;
uitextfield *field3;
uitextfield *field4;
}
@property (nonatomic, retain) iboutlet uitextfield *field1;
@property (nonatomic, retain) iboutlet uitextfield *field2;
@property (nonatomic, retain) iboutlet uitextfield *field3;
@property (nonatomic, retain) iboutlet uitextfield *field4;
@end
复制代码 代码如下:
//
// persistenceviewcontroller.m
// persistence4
//
// created by liu lavy on 11-10-3.
// copyright 2011 __mycompanyname__. all rights reserved.
//
#import "persistenceviewcontroller.h"
#import "persistence4appdelegate.h"
@implementation persistenceviewcontroller
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
-(void) applicationwillresignactive:(nsnotification *)notification {
persistence4appdelegate *appdelegate = [[uiapplication sharedapplication] delegate];
nsmanagedobjectcontext *context = [appdelegate managedobjectcontext];
nserror *error;
for(int i = 1; i <= 4; i++) {
nsstring *fieldname = [nsstring stringwithformat:@"field%d", i];
uitextfield *thefield = [self valueforkey:fieldname];
//创建提取请求
nsfetchrequest *request = [[nsfetchrequest alloc] init];
//创建实体描述并关联到请求
nsentitydescription *entitydescription = [nsentitydescription entityforname:@"line"
inmanagedobjectcontext:context];
[request setentity:entitydescription];
//设置检索数据的条件
nspredicate *pred = [nspredicate predicatewithformat:@"(linenum = %d)", i];
[request setpredicate:pred];
nsmanagedobject *theline = nil;
////检查是否返回了标准匹配的对象,如果有则加载它,如果没有则创建一个新的托管对象来保存此字段的文本
nsarray *objects = [context executefetchrequest:request error:&error];
if(!objects) {
nslog(@"there was an error");
}
//if(objects.count > 0) {
// theline = [objects objectatindex:0];
//} else {
//创建一个新的托管对象来保存此字段的文本
theline = [nsentitydescription insertnewobjectforentityforname:@"line"
inmanagedobjectcontext:context];
[theline setvalue:[nsnumber numberwithint:i] forkey:@"linenum"];
[theline setvalue:thefield.text forkey:@"linetext"];
//}
[request release];
}
//通知上下文保存更改
[context save:&error];
}
// the designated initializer. override if you create the controller programmatically and want to perform customization that is not appropriate for viewdidload.
/*
- (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil {
self = [super initwithnibname:nibnameornil bundle:nibbundleornil];
if (self) {
// custom initialization.
}
return self;
}
*/
// implement viewdidload to do additional setup after loading the view, typically from a nib.
- (void)viewdidload {
persistence4appdelegate *appdelegate = [[uiapplication sharedapplication] delegate];
nsmanagedobjectcontext *context = [appdelegate managedobjectcontext];
//创建一个实体描述
nsentitydescription *entitydescription = [nsentitydescription entityforname:@"line" inmanagedobjectcontext:context];
//创建一个请求,用于提取对象
nsfetchrequest *request = [[nsfetchrequest alloc] init];
[request setentity:entitydescription];
//检索对象
nserror *error;
nsarray *objects = [context executefetchrequest:request error:&error];
if(!objects) {
nslog(@"there was an error!");
}
for(nsmanagedobject *obj in objects) {
nsnumber *linenum = [obj valueforkey:@"linenum"];
nsstring *linetext = [obj valueforkey:@"linetext"];
nsstring *fieldname = [nsstring stringwithformat:@"field%d", [linenum integervalue]];
uitextfield *textfield = [self valueforkey:fieldname];
textfield.text = linetext;
}
[request release];
uiapplication *app = [uiapplication sharedapplication];
[[nsnotificationcenter defaultcenter] addobserver:self
selector:@selector(applicationwillresignactive:)
name:uiapplicationwillresignactivenotification
object:app];
[super viewdidload];
}
/*
// override to allow orientations other than the default portrait orientation.
- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation {
// return yes for supported orientations.
return (interfaceorientation == uiinterfaceorientationportrait);
}
*/
- (void)didreceivememorywarning {
// releases the view if it doesn't have a superview.
[super didreceivememorywarning];
// release any cached data, images, etc. that aren't in use.
}
- (void)viewdidunload {
self.field1 = nil;
self.field2 = nil;
self.field3 = nil;
self.field4 = nil;
[super viewdidunload];
}
- (void)dealloc {
[field1 release];
[field2 release];
[field3 release];
[field4 release];
[super dealloc];
}
@end
5、appsettings
复制代码 代码如下:
nsuserdefaults *defaults = [nsuserdefaults standarduserdefaults];
6、普通文件存储
这种方式即自己将数据通过io保存到文件,或从文件读取。
上一篇: 肌酐高吃什么食物好,应该注意哪些饮食问踢
下一篇: 辣椒辣手了怎么办,今天告诉你!