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];
}
解析過程跟從檔案讀取基本一樣。