记一次保存UIWebView的缓存经历(二)

上篇文章写了点命令行操作SQLite和一些SQLite的C函数。
虽然当时把UIWebView归档至NSData,并且存入SQLite,之后再进行反序列化的想法失败了。
但是对于一般的对象,这个方法还是可以保存所需对象的成员变量。

 

1. 对象归档

    1.1 实现NSCoding接口
        需要被归档的类需要实现NSCoding接口,和- (void) encodeWithCoder:(NSCoder *)aCoder、-(id) initWithCoder:(NSCoder *)aDecoder方法
        People.h

        #import <Foundation/Foundation.h> @interface People : NSObject<NSCoding> { NSString *name; } @property (nonatomic, retain) NSString *name; @end

        People.m

        #import "People.h" @implementation People @synthesize name; - (void) encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:name forKey:@"name"]; } -(id) initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { self.name = [aDecoder decodeObjectForKey:@"name"]; } return self; } @end

 

    1.2 序列化和反序列化

        NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:object];

        People *people = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

 

    1.3 将包含特殊字符的内容(序列化后的结果)存入数据库

 

        NSString *insertStatementNS = [NSString stringWithString: @"insert into /"webView/"/ (kpiId,kpiDate,data)/ values (?, ?, ?)"]; const char *insertStatement = [insertStatementNS UTF8String]; dbrc = sqlite3_prepare_v2 (db, insertStatement, -1, &dbps, NULL); NSLog(@"%@",[NSString stringWithCString:[dataRaw bytes] encoding:NSUTF8StringEncoding]); sqlite3_bind_blob(dbps, 3, [dataRaw bytes], [dataRaw length], NULL); //字段绑定 将NSData中的bytes插入数据库 还有一点 就是下标是从1开始的! sqlite3_bind_text(dbps, 1, [kpiId UTF8String], -1, NULL); sqlite3_bind_text(dbps, 2, [kpiDate UTF8String], -1, NULL); dbrc = sqlite3_step (dbps); sqlite3_finalize (dbps); sqlite3_close(db);

 

你可能感兴趣的:(数据库,sqlite,String,null,encoding,archive)