Objective-C提供了几种常用的数据保存方案
- 属性列表
- 对象序列化和反序列化
- SQLite
- Core Data
属性列表
plist中可存储的类型:NSArray, NSDictionary, NSString, NSData, NSDate, NSNumber,最常用的根类型是NSArray,NSDictionary
这些类提供了读和写的方法, 同样提供的工厂方法
- (id) initWithContentsOfFile : (NSString *) filePath; - (void) writeToFile: (NSString *) filePath atomically: (BOOL) flag;
NSArray *plist = [NSArray arrayWithContentsOfFile: @"/tmp/test.plist"];
[plist writeToFile: @"/tmp/testSaved.plist" atomically: YES];
对象序列化
实现NSCoding协议
@implementation Person - (id) initWithCoder: (NSCoder *) decoder { self = [super initWithCoder: decoder]; if(self) { self.firstName = [decoder decodeObjectForKey: @"firstName"]; } return self; } - (void) encodeWithCoder: (NSCoder *) coder {
[super encodeWithCoder: coder]; [coder encodeObject: self.firstName forKey: @"firstName"]; } @end
NSCoder是抽象类,需要使用它的子类的实现, 如NSKeyedArchiver, NSKeyedUnarchiver
NSData *personData = [NSKeyedArchiver archiverDataWithRootObject: somePerson];
[personData writeToFile: @"/tmp/somePerson.data"];
somePerson = [NSKeyedUnarchiver unarchiveObjectWithData: personData];
上例使用了工厂方法,同样可以使用实例方法
NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data]; [archiver encodeObject: somePerson forKey: "bobData"]; [archiver finishEncoding]; BOOL isSuccess = [data writeToFile: @"/tmp/bob.data" atomically: YES]; [archiver release]; [data release]; NSData *bobData = [[NSData alloc] initWithContentsOfFile: @"/tmp/bob.data"]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: bobData]; somePerson = [unarchiver decodeObjectForKey: @"bobData"]; [unarchiver release]; [bobData release];
SQLite
SQLite是基于文件是数据库,提供了C API,使用字符串为C字符串,不能用NSString
sqlite3 *database; int result = sqlite3_open("/documents/mydata.db", &database);
if(result== SQLITE_OK)
{}
char *errorMsg;
const char *createSql = "CREATE TABLE IF NOT EXISTS Person (ID INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT");
result = sqlite3_exec(database, createSql, NULL, NULL, &errorMsg);
const char *sql = "SELECT * FROM Person WHERE firstName='bob'";
sqlite3_stmt *sqlStatement;
result = sqlite3_prepare_v2(database, sql, -1, &sqlStatement, NULL);
if(result==SQLITE_OK)
{
while(sqlite3_step(sqlStatement) == SQLITE_ROW)
{
// 第二个参数为索引
int id = sqlite3_column_int(sqlStatement, 0);
char *firstName = (char *)sqlite3_column_text(sqlStatement, 1);
}
sqlite3_finalize(sqlStatement);
}
sqlite3_close(database);
绑定变量语法
char *sql = "INSERT INTO Person VALUES(?)"; sqlite3_stmt *statement; result = sqlite3_prepare_v2(database,sql, -1, &statement, NULL); if(result == SQLITE_OK) { sqlite3_bind_text(statement,1, "john", -1, NULL); } if(sqlite3_step(statement) != SQLITE_DONE) { NSLog("check errors"); } sqlite3_finalize(statement);
第四个参数表示数据长度,-1表示整个字符串
最后一个可选的回调函数,用于执行内存清理工作。