做iOS開發(fā)多年,一直都是拿來主義栽连,沒有什么貢獻(xiàn)险领。近段時(shí)間在做知識(shí)梳理的過程中,整理了一些比較實(shí)用的代碼秒紧,模塊化出來分享給大家绢陌。希望各位大佬拍磚,大家共同學(xué)習(xí)提高熔恢。
首先整理出來的是 SEWUserDefaults下面,一個(gè)基于FMDB實(shí)現(xiàn)的UserDefaults,其功能與NSUserDefaults一樣绩聘。你可能會(huì)很奇怪沥割,為什么要重新實(shí)現(xiàn)系統(tǒng)已提供的功能,吃飽了撐的凿菩?或是嫌棄Apple的代碼不夠好机杜?NO!
先說一下項(xiàng)目背景衅谷,為什么要寫這樣一份代碼椒拗。眾所周知,NSUserDefaults是iOS系統(tǒng)提供的用于保存一些簡(jiǎn)單數(shù)據(jù)的工具類获黔。其好處是簡(jiǎn)單方便蚀苛,缺點(diǎn)也就是太簡(jiǎn)單只適合存儲(chǔ)簡(jiǎn)單數(shù)據(jù)。問題是從iOS11開始發(fā)現(xiàn)的玷氏,在擼代碼的過程中發(fā)現(xiàn)有時(shí)候明明存儲(chǔ)到NSUserDefaults成功堵未,但是讀取的時(shí)候卻沒有數(shù)據(jù),這不是坑嗎盏触,說好的信任呢渗蟹?沒辦法块饺,所以就基于FMDB實(shí)現(xiàn)了一個(gè)UserDefaults,即SEWUserDefaults雌芽。
SEWUserDefaults分兩個(gè)部分授艰,SEWUserDefaults和SEWUserDefaults+Database。SEWUserDefaults是提供給開發(fā)者的使用接口世落,其方法與NSUserDefaults中的方法一致淮腾,所以可以很方便的使用。SEWUserDefaults+Database是一個(gè)私有的Category屉佳,用來包裝數(shù)據(jù)庫(kù)增刪改查操作谷朝。
SEWUserDefaults.h如下:
@interface SEWUserDefaults : NSObject
+ (void)openLog;
+ (void)closeLog;
+ (instancetype)standardUserDefaults;
- (nullable id)objectForKey:(NSString *)defaultName;
- (BOOL)setObject:(nullable id)value forKey:(NSString *)defaultName;
- (BOOL)removeObjectForKey:(NSString *)defaultName;
- (nullable NSString *)stringForKey:(NSString *)defaultName;
- (NSInteger)integerForKey:(NSString *)defaultName;
- (float)floatForKey:(NSString *)defaultName;
- (double)doubleForKey:(NSString *)defaultName;
- (BOOL)boolForKey:(NSString *)defaultName;
- (BOOL)setInteger:(NSInteger)value forKey:(NSString *)defaultName;
- (BOOL)setFloat:(float)value forKey:(NSString *)defaultName;
- (BOOL)setDouble:(double)value forKey:(NSString *)defaultName;
- (BOOL)setBool:(BOOL)value forKey:(NSString *)defaultName;
@end
SEWUserDefaults.h中最重要的兩個(gè)方法是 setObject: forKey: 和 objectForKey:兩個(gè)方法,其它所有方法都是這兩個(gè)方法的不同包裝忘古。
先看setObject: forKey: 方法:
- (BOOL)setObject:(nullable id)value forKey:(NSString *)defaultName
{
BOOL result = NO;
if (value && ![value isKindOfClass:[NSNull class]]) {
result = [self replaceIntoValueObject:value forKey:defaultName];
} else {
result = [self removeObjectForKey:defaultName];
}
return result;
}
當(dāng)value不為空時(shí),進(jìn)行數(shù)據(jù)庫(kù)更新(調(diào)用SEWUserDefaults+Database中的replaceIntoValueObject: forKey:方法)诅诱。當(dāng)value為空時(shí)髓堪,刪除對(duì)應(yīng)key的記錄(調(diào)用SEWUserDefaults+Database中的removeObjectForKey:方法)。
objectForKey:則是直接從數(shù)據(jù)庫(kù)中查詢相應(yīng)的記錄:
- (nullable id)objectForKey:(NSString *)defaultName
{
return [self valueObjectForKey:defaultName];
}
SEWUserDefaults+Database.h如下:
@interface SEWUserDefaults (Database)
- (void)createTableIfNotExist;
- (BOOL)replaceIntoValueObject:(id)object forKey:(NSString *)defaultName;
- (BOOL)deleteValueObjectForKey:(NSString *)defaultName;
- (nullable id)valueObjectForKey:(NSString *)defaultName;
@end
其中最重要的兩個(gè)方法為replaceIntoValueObject:forKey:和valueObjectForKey:分別實(shí)現(xiàn)數(shù)據(jù)更新和查詢娘荡。
replaceIntoValueObject:forKey:實(shí)現(xiàn):
- (BOOL)replaceIntoValueObject:(id)object forKey:(NSString *)defaultName
{
NSAssert(object != nil && defaultName != nil, @"數(shù)據(jù)不能為空");
id targetObject = nil;
if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[NSData class]]) {
targetObject = object;
} else {
targetObject = [NSKeyedArchiver archivedDataWithRootObject:object];
}
NSString *sql = [NSString stringWithFormat:@"replace into %@ (%@, %@) values ('%@', '%@')", kTableName, kTableColumnKey, kTableColumnValue, defaultName, object];
__block BOOL executeResult = NO;
[self.databaseQueue inDatabase:^(FMDatabase *db) {
executeResult = [db executeUpdate:sql];
#if DEBUG
if (kLogSwich) {
if (executeResult) {
NSLog(@"SQL 執(zhí)行成功:%@", sql);
} else {
NSLog(@"SQL 執(zhí)行失敻膳浴:%@", sql);
}
}
#endif
}];
return executeResult;
}
在更新數(shù)據(jù)時(shí)NSString和NSNumber可以直接存儲(chǔ),其它類型由NSKeyedArchiver序列化之后存儲(chǔ)炮沐,所以只要實(shí)現(xiàn)了NSCoding協(xié)議的對(duì)象都可以存儲(chǔ)争群。
valueObjectForKey:方法實(shí)現(xiàn):
- (nullable id)valueObjectForKey:(NSString *)defaultName
{
NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@ = '%@'", kTableName, kTableColumnKey, defaultName];
__block id targetObject = nil;
[self.databaseQueue inDatabase:^(FMDatabase *db) {
FMResultSet *resultSet = [db executeQuery:sql];
while ([resultSet next]) {
id object = [resultSet objectForColumn:[kTableColumnValue copy]];
do {
if ([object isKindOfClass:[NSNull class]]) {
break;
}
if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
targetObject = object;
break;
}
if ([object isKindOfClass:[NSData class]]) {
id tempObject = [NSKeyedUnarchiver unarchiveObjectWithData:object];
if (tempObject) {
targetObject = tempObject;
} else {
targetObject = object;
}
break;
}
} while (0);
}
}];
return targetObject;
}
方法執(zhí)行數(shù)據(jù)庫(kù)查詢,遍歷結(jié)果集時(shí)大年,如果是NSString或者NSNumber類型直接返回换薄,如果是NSData類型則進(jìn)行反序列化解析出相應(yīng)對(duì)象后返回。
線程安全性
所有數(shù)據(jù)庫(kù)操作均使用FMDatabaseQueue進(jìn)行翔试,故SEWUserDefaults也是線程安全的轻要。
Podfile
pod 'SEWUserDefaults'
Github
Github地址:https://github.com/sierwan/SEWUserDefaults 歡迎star
小廣告
自己做的一個(gè)免費(fèi)小工具APP哄褒,歡迎下載使用: https://itunes.apple.com/cn/app/isecrets-%E5%AE%89%E5%85%A8%E4%B8%93%E4%B8%9A%E7%9A%84%E5%AF%86%E7%A0%81%E7%AE%A1%E7%90%86%E5%B7%A5%E5%85%B7/id1359152999?mt=8