如果能在 Model 物件上直接呼叫 saveModel 就完成入庫,何必每次手寫 SQL?這個思路背後其實有一套很直觀的對應關係。
換句話說,只要把類別定義好,表結構就跟著定下來了。
@interface TestModel : NSObject @property (assign, nonatomic) NSInteger age; @property (assign, nonatomic) CGFloat height; @property (assign, nonatomic) long distance; @property (assign, nonatomic) double maxDistance; @property (assign, nonatomic) BOOL isOK; @property (assign, nonatomic) char mChar; @property (assign, nonatomic) CGRect rect; @property (assign, nonatomic) CGPoint point; @property (assign, nonatomic) CGSize size; @property (assign, nonatomic) NSRange range; @property (strong, nonatomic) NSNumber *number; @property (strong, nonatomic) NSString *string; @property (strong, nonatomic) UIColor *color; @property (strong, nonatomic) NSDate *date; @property (strong, nonatomic) NSData *data; // 轉為 data 存放 @property (strong, nonatomic) NSValue *value; @property (strong, nonatomic) UIImage *image; @end
對應出來的表結構就類似這樣:
TABLE TestModel (age type, height type, distance type, isOK type, mChar type, ...)
以下方法仍在持續補充中:
+(ModelToTableMap *)getModelToTableMap; +(NSString *)getDBPath; +(NSString *)getTableName; +(NSArray *)getPrimaryKeys; +(NSDictionary *)getPropertyToColumnMap; +(NSDictionary *)getDefaultValueDictionary; +(NSDictionary *)getLengthDictionary; +(NSDictionary *)getCheckValueDictionary; +(NSDictionary *)getIsUniqueDictionary; +(NSDictionary *)getIsNotNullDictionary; +(BOOL)shouldModelToTableMapContainParentProperties; +(BOOL)shouldModelToTableMapContainSelfProperties; +(NSString *)getDateFormatterString; +(NSString *)getDBImagePathWithImageName:(NSString *)imgName; +(NSString *)getDBDataPathWithDataName:(NSString *)dataName; +(BOOL)createTable; +(BOOL)dropTable; +(id)firstModelWhere:(NSObject *)where; +(id)firstModelWhere:(NSObject *)where orderBy:(NSString *)orderBy; +(NSArray *)allModels; +(NSArray *)findModelsWhere:(NSObject *)where; +(NSArray *)findModelsWhere:(NSObject *)where orderBy:(NSString *)orderBy offset:(int)offset count:(int)count; +(BOOL)insertModel:(NSObject *)model; +(BOOL)insertModelWhenNotExists:(NSObject *)model; +(BOOL)deleteModel:(NSObject *)model; +(BOOL)deleteModelsWhere:(NSObject *)where; +(BOOL)updateModelsWithModel:(NSObject *)model where:(NSObject *)where; +(BOOL)updateModelsWithDictionary:(NSDictionary *)dic where:(NSObject *)where; +(BOOL)isModelExists:(NSObject *)model; - (BOOL)saveModel; - (BOOL)deleteModel; - (BOOL)updateModel:(NSObject *)theNewModel; - (BOOL)updateModelWithDictionary:(NSDictionary *)dic;
從命名就能看出設計意圖:類別方法偏向批次與查詢,實例方法則對應單筆資料的增刪改。
先建立物件並指派屬性:
TestModel *model = [[TestModel alloc] init]; model.age = 20; model.image = [UIImage imageNamed:@"img.jpg"];
接著四個基本操作各一行:
// 新增
[model saveModel];
// 刪除
[model deleteModel];
// 修改(只更新指定欄位)
[model updateModelWithDictionary:@{@"age" : @(21)}];
// 查詢全部
[TestModel allModels];
這種「一行搞定資料庫」的封裝在小型專案中開發效率極高,但用在正式產品前,建議先確認幾件事:查詢條件是否有做參數綁定(避免 SQL injection)、大量資料寫入時是否包在 transaction 裡、以及型別對應是否涵蓋你專案實際會用到的所有屬性型別。封裝在降低門檻的同時,也把這些細節藏起來了,理解底層在做什麼仍然必要。