原帖地址
如果将字典或数组直接存储在数据库中,会将数组或字典转化成字符串,所以可以使用归档与反归档的方法将数据进行编码和解码成二进制数据进行存储,而在数据库中需要使用blob类型存储二进制数据。
如下面的例子:
在Shop.m中
#import "Shop.h"
@implementation Shop
#pragma mark 编码
-(void)encodeWithCoder:(NSCoder *)enCoder {
[enCoder encodeObject:self.name forKey:@"name"];
[enCoder encodeDouble:self.price forKey:@"price"];
}
#pragma mark 解码
- (instancetype)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if (self) {
self.name = [decoder decodeObjectForKey:@"name"];
self.price = [decoder decodeDoubleForKey:@"price"];
}
return self;
}
-(NSString *)description {
return [NSString stringWithFormat:@"%@--%f",self.name, self.price];
}
@end
在ViewController中
初始化数据库
//初始化数据库
-(void)initDatabase {
//初始化
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shop.sqlite"];
self.db = [FMDatabase databaseWithPath:path];
[self.db open];
//创表
//数据库中blob是二进制对象
[self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shop(id integer PRIMARY KEY, shop blob NOT NULL)"];
}
添加数据
//添加数据
- (void)addShops {
for (int i = 0; i < 1000; i++) {
Shop *shop = [[Shop alloc] init];
shop.name = [NSString stringWithFormat:@"商品--%d", i];
shop.price = arc4random() % 10000;
//要将一个对象存进数据库的blob字段,最先转化为NSData
//一个对象要遵守NSCoding协议,实现协议中相应的方法,才能转化为NSData
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:shop];
[self.db executeUpdateWithFormat:@"INSERT INTO t_shop(shop) VALUES (%@);",data];
}
}
读取数据
// 读取数据
-(void)readShos {
FMResultSet *set = [self.db executeQuery:@"SELECT * FROM t_shop LIMIT 10;"];
while (set.next) {
NSData *data = [set objectForColumnName:@"shop"];
Shop *shop = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@---%f",shop.name, shop.price);
}
}