#import "SXViewController.h"
#import "SXShop.h"
#import "FMDB.h"
@interface SXViewController ()
@property (nonatomic, strong) FMDatabase *db;
@end
@implementation SXViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self setup];
[self readShops];
}
- (void)setup
{
// 初始化
NSString *path = @"/Users/apple/Desktop/shops.data";
self.db = [FMDatabase databaseWithPath:path];
[self.db open];
// 2.创表
[self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, shop blob NOT NULL);"];
}
- (void)readShops
{
FMResultSet *set = [self.db executeQuery:@"SELECT * FROM t_shop LIMIT 10,10;"];
while (set.next) {
NSData *data = [set objectForColumnName:@"shop"];
SXShop *shop = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@", shop);
}
}
- (void)addShops
{
for (int i = 0; i<100; i++) {
SXShop *shop = [[SXShop alloc] init];
shop.name = [NSString stringWithFormat:@"商品--%d", i];
shop.price = arc4random() % 10000;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:shop];
[self.db executeUpdateWithFormat:@"INSERT INTO t_shop(shop) VALUES (%@);", data];
}
}
@end