IOS保存对象数据方法之--文件保存和SQLite保存

   iOS编程经常有要存数据的需求,例如这次做的购物app,希望把用户放在购物车里的数据存起来,以便用户下次运行程序时还可以看到购物车保存的商品,保存数据的几种方式可以参考另一个博主的文章:

                http://blog.csdn.net/tianyitianyi1/article/details/7713103

    考虑到购物车的数据一般不多,而且想保存的是对象数据,权衡利弊,可以用写文件的方法保存

如下,在 applicationWillTerminate:(UIApplication *)application 方法保存数据到本地文件,文件名随意定义

其中_carGoodsList是存储购物车商品CartGoods对象的数组,

具体实现原理:先用PrintObject类把对象打印成NSString(字典格式的NSString,然后把NSString数据存在arrayyy数组里面,最后是把数组写到文件,这么麻烦是因为写到文件里面的arrayyy数组不能包含其他自定义的对象(麻烦!!)

    //将购物车的商品数据保存在本地文件

     _carGoodsList = [[[GlobalVariablessharedInstance]cartList] allValues];

   NSData *jsonData = [NSDatanew];

    NSMutableArray *arrayyy = [NSMutableArraynew];

    for (CartGoods *goodsin _carGoodsList) {

        jsonData = [PrintObjectgetJSON:goods options:NSJSONWritingPrettyPrintederror:nil];

        NSString *tempStr = [[NSStringalloc] initWithData:jsonDataencoding:NSUTF8StringEncoding];

        [arrayyyaddObject:tempStr];

    }

    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject];

    NSString *path=[docPathstringByAppendingPathComponent:@"carGoodsList.en"];

    [NSKeyedArchiverarchiveRootObject:arrayyy toFile:path];



然后是反过程读取并解析文件,根据数据还原所有CartGoods对象,初始化购物车数据(解析数据可以放到程序的主页进行)

//从本地加载购物车数据并初始化购物车数量

    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject];

    NSString *path=[docPathstringByAppendingPathComponent:@"carGoodsList.en"];

   NSArray *tempArray =[NSKeyedUnarchiverunarchiveObjectWithFile:path];

   for (NSString *dictStrin tempArray) {

       NSError *error = nil;

        NSDictionary *dict = [NSJSONSerializationJSONObjectWithData: [dictStr dataUsingEncoding:NSUTF8StringEncoding]

                                                            options: NSJSONReadingMutableContainers

                                                              error: &error];

       if (error) {

           DebugLog(@"解析失败!");

        }else {

           CartGoods *goods = [CartGoodsnew];

            [goodssetDict:dict];

            [mallmapAppaddCartGoods:goods];//购物车添加商品

            

        }

        

    }

//购物车数量提示

    [[NSNotificationCenterdefaultCenter] postNotificationName:@"setBadge"object:@"3"];


反过程用到NSJSONSerialization把符合字典数据结构的Nsstring转换为NSDictionary数据。





第二种试了下保存在数据库里面,跟保存在文件思路类似,至于两个哪个性能会更好,目前不太清楚。。。

数据库保存方法:同样的思路,先把购物车商品对象编码成nsstring,然后根据商品id goodsid为索引直接插入数据库,
要注意的是,保存的方法是先删除旧的数据,然后插入新的,因为jsondictStr是一串比较长的nsstring数据,对应修改某个值比较麻烦,干脆替换整个数据!!

-(void)updateDataCacheOfcarGoods:(CartGoods *) cartGoods {

    

    //更新数据库数据

    NSData *jsonData = [NSData new];

    jsonData = [PrintObject getJSON:cartGoods options:NSJSONWritingPrettyPrinted error:nil];

    NSString *jsondictStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    

    DB *db = [DB initMallmapDB:NO];

    

    //删除旧的缓存

    [db executeUpdate:@"delete from car_goods where goodsid =?", cartGoods.goods_id];

    

    插入新的缓存

    [db executeUpdate:@"insert into car_goods (goodsid, json_dictstr) values (?,?)", cartGoods.goods_id, jsondictStr];

    

    [db close];

}


读取的过程也差不多:


-(void)loadCargoodsData{

    //第二种方法是把数据库存储在数据库里面

    DB *db = [DB initMallmapDB:NO];

    FMResultSet *rset= [db executeQuery:@"select * from car_goods"];

    NSError *error = nil;

    NSDictionary *dict = [NSDictionary new];

    while ([rset next]) {

        NSString *goodsDictstr = [rset stringForColumn:@"json_dictstr"];

 

        dict  = [NSJSONSerialization JSONObjectWithData: [goodsDictstr dataUsingEncoding:NSUTF8StringEncoding]

                                                options: NSJSONReadingMutableContainers

                                                  error: &error];

        if (error) {

            DebugLog(@"数据解析失败!");

        }else {

            CartGoods *goods = [CartGoods new];

            [goods setDict:dict];

            [mallmapApp addCartGoods:goods];

            

        }


    }

    [db close];


}


解析过程跟从文件读取基本一样。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值