您的位置:首页 > 移动开发 > IOS开发

ios存储数据的几种方式

2012-09-27 14:30 302 查看
NSInteger page;

1.Property List

#define LIST_FILE_NAME @"Property.list"

//Read
- (void)restoreDataWithProperty {
NSString *path = [self dataFilePathWithName:LIST_FILE_NAME];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
NSNumber *num = [array objectAtIndex:0];
page = [num integerValue];
} else {
page = 1;
}
}

//Write
- (void)saveDataWithProperty {
NSString *myFile = [self dataFilePathWithName:LIST_FILE_NAME];
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *num = [NSNumber numberWithInteger:page];
[array addObject:num];
[array writeToFile:myFile atomically:YES];
}


2.NSUserDefaults (Support Type:NSData,NSString,NSNumber,NSDate,NSArray,NSDictionary)

#define PAGE @"page"

//Read
- (void)restoreDataWithUserDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger p = [[defaults objectForKey:PAGE] integerValue];
if (0 == p) {
page = 1;
} else {
page = p;
}
}

//Write
- (void)saveDataWithUserDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *num = [NSNumber numberWithInteger:page];
[defaults setObject:num forKey:PAGE];
[defaults synchronize];
}


3.Object Archive (Can save the Object data type, the Obejct must implement the NSCoding and NSCopying protocol)

#define ARCHIVE_FILE_PATH @"archive"
#define NUMBER_KEY @"number"

- (void)encodeWithCoder:(NSCoder *)aCoder{
NSLog(@"in encode with coder");
NSNumber *num = [[NSNumber numberWithInteger:self.page] autorelease];
[aCoder encodeObject:num forKey:NUMBER_KEY];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
NSLog(@"in init with coder");
if (self = [super init]) {
NSNumber *num = [aDecoder decodeObjectForKey:NUMBER_KEY];
page = [num integerValue];
}
return self;
}

- (id)copyWithZone:(NSZone *)zone {
NSLog(@"in copy with zone");
StickyNotesViewController *controller = [[[[self class] allocWithZone:zone] init] autorelease];
NSNumber *num = [[NSNumber numberWithInteger:self.page] autorelease];
controller.page = [[num copyWithZone:zone] integerValue];
return controller;
}

//Read
- (void)restoreDataWithObjectArchive {
NSString *path = [self dataFilePathWithName:ARCHIVE_FILE_PATH];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
StickyNotesViewController *controller = [unarchive decodeObjectForKey:NUMBER_KEY];
[unarchive finishDecoding];
page = controller.page;
}
}

//Write
- (void)saveDataWithObjectArchive {
StickyNotesViewController *controller = [[StickyNotesViewController alloc] init];
controller.page = self.page;
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archive encodeObject:controller forKey:NUMBER_KEY];
[archive finishEncoding];
[data writeToFile:[self dataFilePathWithName:ARCHIVE_FILE_PATH] atomically:YES];
}


4.Sqlite

#define SQLITE_DB_NAME @"my_data.db"

//Read
- (void)restoreDataWithSqlite {
NSString *path = [self dataFilePathWithName:SQLITE_DB_NAME];
sqlite3 *database;
int result = sqlite3_open([path UTF8String], &database);
if (SQLITE_OK != result) {
sqlite3_close(database);
NSAssert(0, @"Failed to open database");
}

char *errorMsg;
char *createTable = "CREATE TABLE IF NOT EXISTS LX(ROW INTEGER PRIMARY KEY, DATA INTEGER);";
int result2 = sqlite3_exec(database, createTable, NULL, NULL, &errorMsg);
if (SQLITE_OK != result2) {
sqlite3_close(database);
NSAssert(0, @"Failed to create the table: %s", errorMsg);
}
char *query = "SELECT ROW, DATA FROM LX ORDER BY ROW";
sqlite3_stmt *stmt;
int result3 = sqlite3_prepare_v2(database, query , -1, &stmt, nil);
if (SQLITE_OK == result3) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
int row = sqlite3_column_int(stmt, 0);
int data = sqlite3_column_int(stmt, 1);
page = data;
NSLog(@"row=%d ,data=%d",row, data);
}
sqlite3_finalize(stmt);
}
sqlite3_close(database);
}

//Write
- (void)saveDataWithSqlite {
sqlite3 *database;
int result = sqlite3_open([[self dataFilePathWithName:SQLITE_DB_NAME] UTF8String], &database);
if (result != SQLITE_OK) {
sqlite3_close(database);
NSLog(@"Failed open the database");
NSAssert(0, @"Failed to open the database");
}
char *update = "INSERT OR REPLACE INTO LX VALUES(?, ?);";
sqlite3_stmt *stmt;
int result2 = sqlite3_prepare_v2(database, update, -1, &stmt, nil);
if (result2 == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, 1);
sqlite3_bind_int(stmt, 2, page);
} else {
NSLog(@"Failed to prepare statement");
NSAssert1(0, @"error msg: %s", sqlite3_errmsg(database));
}
int result3 = sqlite3_step(stmt);
if (SQLITE_DONE != result3) {
NSAssert1(0, @"Error updating table: %d", result3);
}
sqlite3_finalize(stmt);
sqlite3_close(database);
}


//get file path by name
- (NSString *)dataFilePathWithName:fileName {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *myFile = [docPath stringByAppendingPathComponent:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:myFile]) {

} else {
//[[NSFileManager defaultManager] createFileAtPath:myFile contents:nil attributes:nil];
}
return myFile;
}


以下关于sqlite3的讲解内容转自

http://blog.csdn.net/m_changgong/article/details/8284135 作者:张燕广



注1:sqlite3_open():打开数据库

在操作数据库之前,首先要打开数据库。

这个函数打开一个sqlite数据库文件的连接并且返回一个数据库连接对象。

第1个参数:数据文件路径必须用C风格字符串(不能用NSString),[filePath UTF8String]将filePath转换为C风格字符串。

第2个参数:是返回的数据库连接对象。

备注2:sqlite3_exec():执行SQL语句

第1个参数:数据库指针,是前面open函数得到的指针

第2个参数:const char *sql是一条sql 语句,以\0结尾。

第3个参数:sqlite3_callback 是回调,当这条语句执行之后,sqlite3会调用这个回调函数。

第4个参数:void*是一个指针,可以传递任何一个指针参数到这里,这个参数最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL

备注3:sqlite3_prepare_v2():将sql文本转换成一个准备语句(prepared statement)对象,同时返回这个对象的指针

第1个参数:数据库指针,是前面open函数得到的指针

第2个参数:sql语句,必须是C风格字符串

第3个参数:如果该参数小于0,则函数取出zSql中从开始到第一个0终止符的内容;如果nByte不是负的,那么它就是这个函数能从zSql中读取的字节数的最大值。如果nBytes非负,zSql在第一次遇见’/000/或’u000’的时候终止

第4个参数:上面提到zSql在遇见终止符或者是达到设定的nByte之后结束,假如zSql还有剩余的内容,那么这些剩余的内容被存放到pZTail中,不包括终止符

备注4:sqlite3_step()

这个过程用于执行有前面sqlite3_prepare创建的准备语句。这个语句执行到结果的第一行可用的位置。继续前进到结果的第二行的话,只需再次调用sqlite3_setp()。继续调用sqlite3_setp()直到这个语句完成,那些不返回结果的语句(如:INSERT,UPDATE,或DELETE),sqlite3_step()只执行一次就返回

备注5:sqlite3_column_text()

从结果集中获取各列的值,需要注意的是:第一列的索引是0。

备注6:
sqlite3_finalize()

这个过程销毁前面被sqlite3_prepare创建的准备语句,每个准备语句都必须使用这个函数去销毁以防止内存泄露。

在空指针上调用这个函数没有什么影响,同时可以在准备语句的生命周期的任一时刻调用这个函数:在语句被执行前,一次或多次调用

sqlite_reset之后,或者在sqlite3_step任何调用之后。

备注7:sqlite3_close()

关闭前面使用sqlite3_open打开的数据库连接,任何与这个连接相关的准备语句必须在调用这个关闭函数之前被释放掉。

备注8:sqlite3_bind_text()

第1个参数:指向在sqlite3_prepare_v2()调用中使用的sqlite3_stme。

第2个参数:所绑定的变量的索引(sql语句中第一个问号的索引),需要注意的是:第一个问号的索引是1,而不是0。

第3个参数:只有少数绑定函数,比如用于绑定文本或二进制数据的绑定函数,这个参数用来设定传递数据的长度。对于C字符串,可以传递-1来代替字符串的长度,意思是要是要使用整个字符串。
第4个参数:回调函数,一般用于在语句执行后做内存清理相关的工作。可以设置为NULL。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息