十一岁的加重songxing10000…… ------ 回到博主首页

将任意对象存进数据库

#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

 

posted @ 2015-07-20 23:54  songxing10000  阅读(302)  评论(0编辑  收藏  举报