IOS本地持久化有4種:屬性列表、對(duì)象歸檔、SQLite3和Core Data;
其中屬性列表和SQlite3是本人強(qiáng)烈推薦的。對(duì)象歸檔較為繁瑣,coreData沒有用過暫不評(píng)價(jià)。
1.屬性列表簡單說一下:最普遍用的最廣泛的持久化方法;
- 1).分開存取
// 存
[[NSUserDefaults standardUserDefaults] setInteger:userID forKey:@”userID”];
[[NSUserDefaults standardUserDefaults] setObject:name forKey:@”name”];
// 取
NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey:@”userID”];
NSString * name = [[NSUserDefaults standardUserDefaults] stringForKey:@”name”]; - 2).按對(duì)象存取
// 存
[[NSUserDefaults standardUserDefaults] setObject:self forKey:@”user”];
// 取
User * u = [[NSUserDefaults standardUserDefaults] [objectForKey”@”user];
2.好了進(jìn)入今天的正題~數(shù)據(jù)庫Sqlite3
說到SQlite3嵌入式數(shù)據(jù)庫不得不提一個(gè)強(qiáng)大的第三方FMDB
有FMDB,OC與SQlite的交互變得不那么困難,化繁為簡。但是很多小伙伴對(duì)sqlite語法很陌生,導(dǎo)致FMDB無緣無故的坑自己。
下面我就來簡單分享自己對(duì)FMDB的理解以及IOS數(shù)據(jù)庫本地持久化的萬能常用語句。-
最開始我們建一個(gè)單例類來創(chuàng)建和管理數(shù)據(jù)庫。
如下:
@implementation DataBaseManagerShoppingCar
{
//數(shù)據(jù)庫管理對(duì)象
FMDatabase *_fmdb;
}
-(instancetype)init{
//1.拋異常
@throw [NSException exceptionWithName:@"DataBaseManagerShoppingCar" reason:@"不能調(diào)用初始化方法" userInfo:nil];
return self;
//2.斷言,判定言論,程序崩潰
// NSAssert(false, @"DataBaseManager無法調(diào)用該方 法");
}
//重新實(shí)現(xiàn)初始化方法
-(instancetype)initWithPrivate
{
if (self =[super init]) {
[self createDataBase];
}
return self;
}+(instancetype)sharedManager { static DataBaseManagerShoppingCar *manager =nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (!manager) { manager =[[DataBaseManagerShoppingCar alloc]initWithPrivate]; } }); return manager; // //2. // @synchronized(self){ // if (!manager) { // manager =[[self alloc]initPrivate]; // } // } } //初始化數(shù)據(jù)庫 -(void)createDataBase { //獲取沙箱路徑下的Documents NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *dbPath =[[documentsPath fir stObject]stringByAppendingPathComponent:@"ShoppingCar.db"]; NSLog(@"%@",dbPath); if (!_fmdb) { //創(chuàng)建數(shù)據(jù)庫管理對(duì)象 _fmdb =[[FMDatabase alloc]initWithPath:dbPath]; } //打開數(shù)據(jù)庫 if ([_fmdb open]) { //創(chuàng)建數(shù)據(jù)庫表 [_fmdb executeUpdate:@"create table if not exists ShoppingCar (productId integer, productName str, thumb str,type integer,num integer,unitPrice double,farmId integer,deliveryWeekIndex integer,payType integer);"]; } }
增刪查
判斷APPID對(duì)應(yīng)的數(shù)據(jù)是否存在
-(BOOL)isExistsProductId:(NSInteger)productId
{
FMResultSet * rs =[_fmdb executeQuery:@"select *from ShoppingCar where productId =?",@(productId)];
// 判斷結(jié)果集是否存在
// if ([rs next]) {
// return YES;
// }
// else{
// return NO;
// }
return [rs next];
}-
添加數(shù)據(jù)
-(BOOL)insertProductId:(NSInteger)productId ProductName:(NSString )productName Thumb:(NSString *)thumb Type:(NSInteger)type Num:(NSInteger)num UnitPrice:(double)unitPrice FarmId:(NSInteger)farmId DeliveryWeekIndex:(NSInteger)deliveryWeekIndex PayType:(NSInteger)payType
{
//判斷AppId在數(shù)據(jù)庫中是否存在
//這里要特別提出來說一下,問號(hào)代表的是對(duì)象,如果你存的常量請(qǐng)先轉(zhuǎn)成對(duì)象存進(jìn)去。比如@(Float) 還有
if(![self isExistsProductId:productId]){
//如果不存在
BOOL success =[_fmdb executeUpdate:@"insert into ShoppingCar values(?,?,?,?,?,?,?,?,?)",@(productId),productName,thumb,@(type),@(num),@(unitPrice),@(farmId),@(deliveryWeekIndex),@(payType)];
return success;
}
return YES;
}
-(BOOL)removeAllobjects
{
BOOL succese = [_fmdb executeUpdate:@"delete from ShoppingCar"];
return succese;
}
-(BOOL)removeProductId:(NSInteger)productId
{
BOOL succese =[_fmdb executeUpdate:@"delete from ShoppingCar where productId=?",@(productId)];
return succese;
}
-(managerModel *)selectCurrentModelWithProductId: (NSInteger)productId
{
FMResultSet *rs =[_fmdb executeQuery:@"select *from ShoppingCar where productId =?",@(productId)];
managerModel *model =[[managerModel alloc]init];
while([rs next]){
model.productId =[rs intForColumn:@"productId"];
model.productName =[rs stringForColumn:@"productName"];
model.thumb =[rs stringForColumn:@"thumb"];
model.type =[rs intForColumn:@"type"];
model.num =[rs intForColumn:@"num"];
model.unitPrice =[rs doubleForColumn:@"unitPrice"];
model.farmId =[rs intForColumn:@"farmId"];
model.deliveryWeekIndex =[rs intForColumn:@"deliveryWeekIndex"];
model.payType =[rs intForColumn:@"payType"];
}
return model;
}-(NSArray *)selectAllApps { //從表中獲取所有數(shù)據(jù) FMResultSet *rs =[_fmdb executeQuery:@"select *from ShoppingCar"]; //遍歷結(jié)果集 NSMutableArray *apps =[NSMutableArray array]; while([rs next]){ managerModel *model =[[managerModel alloc]init]; model.productId =[rs intForColumn:@"productId"]; model.productName =[rs stringForColumn:@"productName"]; model.thumb =[rs stringForColumn:@"thumb"]; model.type =[rs intForColumn:@"type"]; model.num =[rs intForColumn:@"num"]; model.unitPrice =[rs doubleForColumn:@"unitPrice"]; model.farmId =[rs intForColumn:@"farmId"]; model.deliveryWeekIndex =[rs intForColumn:@"deliveryWeekIndex"]; model.payType =[rs intForColumn:@"payType"]; [apps addObject:model]; } return [apps copy]; } //修改數(shù)據(jù) -(BOOL)updateProductId:(NSInteger)productId Num: (NSInteger)num { BOOL succese =[_fmdb executeUpdate:@" update ShoppingCar set num =? where productId=?",@(num),@(productId)]; return succese; } FMDB的三種查詢方法
-(FMResultSet )executeQuery:(NSString)sql, ...
- (FMResultSet )executeQueryWithFormat:(NSString)format, ...
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments
// executeUpdate : 不確定的參數(shù)用?來占位
[self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);", name, @(arc4random_uniform(40))];
//也可以這樣表示
//NSString *tableName =@"t_student (name, age)";
//[self.db executeUpdate:[NSString stringWithFormat:@"insert into %@ VALUES(?,?)" ,tableName],name, @(arc4random_uniform(40))];
[self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);" withArgumentsInArray:@[name, @(arc4random_uniform(40))]];
// executeUpdateWithFormat : 不確定的參數(shù)用%@、%d等來占位
//此處一定要注意Format后面不是單純的字符串NSString,不能隨便的組裝字符串,它只能接Values括號(hào)里面的占位參數(shù),不能更改Values前面的參數(shù),例如:
錯(cuò)誤的表達(dá):
[self.db executeUpdateWithFormat:@"INSERT INTO %@ VALUES (%@, %d);", @"t_student (name, age)",name, arc4random_uniform(40)];
正確表達(dá):
[self.db executeUpdateWithFormat:@"INSERT INTO t_student (name, age) VALUES (%@, %d);", name, arc4random_uniform(40)];