码迷,mamicode.com
首页 > 数据库 > 详细

将任意对象存进数据库

时间:2015-07-21 01:03:30      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

#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

 

将任意对象存进数据库

标签:

原文地址:http://www.cnblogs.com/songxing10000/p/4663152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!