BGTool.m 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. //
  2. // BGTool.m
  3. // BGDB
  4. //
  5. // Created by huangzhibiao on 17/2/16.
  6. // Copyright © 2017年 Biao. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #import <CoreData/CoreData.h>
  10. #import "BGTool.h"
  11. #import "BGDB.h"
  12. #import "NSCache+BGCache.h"
  13. #define SqlText @"text" //数据库的字符类型
  14. #define SqlReal @"real" //数据库的浮点类型
  15. #define SqlInteger @"integer" //数据库的整数类型
  16. //#define SqlBlob @"blob" //数据库的二进制类型
  17. #define BGValue @"BGValue"
  18. #define BGData @"BGData"
  19. #define BGArray @"BGArray"
  20. #define BGSet @"BGSet"
  21. #define BGDictionary @"BGDictionary"
  22. #define BGModel @"BGModel"
  23. #define BGMapTable @"BGMapTable"
  24. #define BGHashTable @"BGHashTable"
  25. #define bg_typeHead_NS @"@\"NS"
  26. #define bg_typeHead__NS @"@\"__NS"
  27. #define bg_typeHead_UI @"@\"UI"
  28. #define bg_typeHead__UI @"@\"__UI"
  29. //100M大小限制.
  30. #define MaxData @(838860800)
  31. //模型深层嵌套的时候使用
  32. #define DEPTH_MODEL 1
  33. //模型非深层嵌套的时候使用(默认)
  34. #define SHALLOW_MODEL 2
  35. #define MODEL_LEVEL SHALLOW_MODEL
  36. /**
  37. * 遍历所有类的block(父类)
  38. */
  39. typedef void (^BGClassesEnumeration)(Class c, BOOL *stop);
  40. static NSSet *foundationClasses_;
  41. @implementation BGTool
  42. /**
  43. 封装处理传入数据库的key和value.
  44. */
  45. NSString* bg_sqlKey(NSString* key){
  46. return [NSString stringWithFormat:@"%@%@",BG,key];
  47. }
  48. /**
  49. 转换OC对象成数据库数据.
  50. */
  51. NSString* bg_sqlValue(id value){
  52. if([value isKindOfClass:[NSNumber class]]) {
  53. return value;
  54. }else if([value isKindOfClass:[NSString class]]){
  55. return [NSString stringWithFormat:@"'%@'",value];
  56. }else{
  57. NSString* type = [NSString stringWithFormat:@"@\"%@\"",NSStringFromClass([value class])];
  58. value = [BGTool getSqlValue:value type:type encode:YES];
  59. if ([value isKindOfClass:[NSString class]]) {
  60. return [NSString stringWithFormat:@"'%@'",value];
  61. }else{
  62. return value;
  63. }
  64. }
  65. }
  66. /**
  67. 根据keyPath和Value的数组, 封装成数据库语句,来操作库.
  68. */
  69. NSString* bg_keyPathValues(NSArray* keyPathValues){
  70. return [BGTool getLikeWithKeyPathAndValues:keyPathValues where:NO];
  71. }
  72. /**
  73. 自定义数据库名称.
  74. */
  75. void bg_setSqliteName(NSString*_Nonnull sqliteName){
  76. if (![sqliteName isEqualToString:[BGDB shareManager].sqliteName]) {
  77. [BGDB shareManager].sqliteName = sqliteName;
  78. }
  79. }
  80. /**
  81. 删除数据库文件
  82. */
  83. BOOL bg_deleteSqlite(NSString*_Nonnull sqliteName){
  84. return [BGDB deleteSqlite:sqliteName];
  85. }
  86. /**
  87. 设置操作过程中不可关闭数据库(即closeDB函数无效).
  88. 默认是NO.
  89. */
  90. void bg_setDisableCloseDB(BOOL disableCloseDB){
  91. if ([BGDB shareManager].disableCloseDB != disableCloseDB){//防止重复设置.
  92. [BGDB shareManager].disableCloseDB = disableCloseDB;
  93. }
  94. }
  95. /**
  96. 手动关闭数据库.
  97. */
  98. void bg_closeDB(){
  99. BOOL closeFlag = [BGDB shareManager].disableCloseDB;
  100. [BGDB shareManager].disableCloseDB = NO;
  101. [[BGDB shareManager] closeDB];
  102. [BGDB shareManager].disableCloseDB = closeFlag;
  103. }
  104. /**
  105. 设置调试模式
  106. @debug YES:打印调试信息, NO:不打印调试信息.
  107. */
  108. void bg_setDebug(BOOL debug){
  109. if ([BGDB shareManager].debug != debug){//防止重复设置.
  110. [BGDB shareManager].debug = debug;
  111. }
  112. }
  113. /**
  114. 事务操作.
  115. @return 返回YES提交事务, 返回NO回滚事务.
  116. */
  117. void bg_inTransaction(BOOL (^ _Nonnull block)()){
  118. [[BGDB shareManager] inTransaction:block];
  119. }
  120. /**
  121. 清除缓存
  122. */
  123. void bg_cleanCache(){
  124. [[NSCache bg_cache] removeAllObjects];
  125. }
  126. /**
  127. json字符转json格式数据 .
  128. */
  129. +(id)jsonWithString:(NSString*)jsonString {
  130. NSAssert(jsonString,@"数据不能为空!");
  131. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  132. NSError *err;
  133. id dic = [NSJSONSerialization JSONObjectWithData:jsonData
  134. options:NSJSONReadingMutableContainers
  135. error:&err];
  136. NSAssert(!err,@"json解析失败");
  137. return dic;
  138. }
  139. /**
  140. 字典转json字符 .
  141. */
  142. +(NSString*)dataToJson:(id)data{
  143. NSAssert(data,@"数据不能为空!");
  144. NSError *parseError = nil;
  145. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:&parseError];
  146. return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  147. }
  148. + (NSSet *)foundationClasses
  149. {
  150. if (foundationClasses_ == nil) {
  151. // 集合中没有NSObject,因为几乎所有的类都是继承自NSObject,具体是不是NSObject需要特殊判断
  152. foundationClasses_ = [NSSet setWithObjects:
  153. [NSURL class],
  154. [NSDate class],
  155. [NSValue class],
  156. [NSData class],
  157. [NSError class],
  158. [NSArray class],
  159. [NSDictionary class],
  160. [NSString class],
  161. [NSAttributedString class], nil];
  162. }
  163. return foundationClasses_;
  164. }
  165. + (void)bg_enumerateClasses:(__unsafe_unretained Class)srcCla complete:(BGClassesEnumeration)enumeration
  166. {
  167. // 1.没有block就直接返回
  168. if (enumeration == nil) return;
  169. // 2.停止遍历的标记
  170. BOOL stop = NO;
  171. // 3.当前正在遍历的类
  172. Class c = srcCla;
  173. // 4.开始遍历每一个类
  174. while (c && !stop) {
  175. // 4.1.执行操作
  176. enumeration(c, &stop);
  177. // 4.2.获得父类
  178. c = class_getSuperclass(c);
  179. if ([self isClassFromFoundation:c]) break;
  180. }
  181. }
  182. + (BOOL)isClassFromFoundation:(Class)c
  183. {
  184. if (c == [NSObject class] || c == [NSManagedObject class]) return YES;
  185. __block BOOL result = NO;
  186. [[self foundationClasses] enumerateObjectsUsingBlock:^(Class foundationClass, BOOL *stop) {
  187. if ([c isSubclassOfClass:foundationClass]) {
  188. result = YES;
  189. *stop = YES;
  190. }
  191. }];
  192. return result;
  193. }
  194. /**
  195. 根据类获取变量名列表
  196. @onlyKey YES:紧紧返回key,NO:在key后面添加type.
  197. */
  198. +(NSArray*)getClassIvarList:(__unsafe_unretained Class)cla Object:(_Nullable id)object onlyKey:(BOOL)onlyKey{
  199. //获取缓存的属性信息
  200. NSCache* cache = [NSCache bg_cache];
  201. NSString* cacheKey;
  202. cacheKey = onlyKey?[NSString stringWithFormat:@"%@_IvarList_yes",NSStringFromClass(cla)]:[NSString stringWithFormat:@"%@_IvarList_no",NSStringFromClass(cla)];
  203. NSArray* cachekeys = [cache objectForKey:cacheKey];
  204. if(cachekeys){
  205. return cachekeys;
  206. }
  207. NSMutableArray* keys = [NSMutableArray array];
  208. if(onlyKey){
  209. [keys addObject:bg_primaryKey];
  210. [keys addObject:bg_createTimeKey];
  211. [keys addObject:bg_updateTimeKey];
  212. }else{
  213. //手动添加库自带的自动增长主键ID和类型q
  214. [keys addObject:[NSString stringWithFormat:@"%@*q",bg_primaryKey]];
  215. //建表时此处加入额外的两个字段(createTime和updateTime).
  216. [keys addObject:[NSString stringWithFormat:@"%@*@\"NSString\"",bg_createTimeKey]];
  217. [keys addObject:[NSString stringWithFormat:@"%@*@\"NSString\"",bg_updateTimeKey]];
  218. }
  219. [self bg_enumerateClasses:cla complete:^(__unsafe_unretained Class c, BOOL *stop) {
  220. unsigned int numIvars; //成员变量个数
  221. Ivar *vars = class_copyIvarList(c, &numIvars);
  222. for(int i = 0; i < numIvars; i++) {
  223. Ivar thisIvar = vars[i];
  224. NSString* key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];//获取成员变量的名
  225. if ([key hasPrefix:@"_"]) {
  226. key = [key substringFromIndex:1];
  227. }
  228. if (!onlyKey) {
  229. //获取成员变量的数据类型
  230. NSString* type = [NSString stringWithUTF8String:ivar_getTypeEncoding(thisIvar)];
  231. key = [NSString stringWithFormat:@"%@*%@",key,type];
  232. }
  233. [keys addObject:key];//存储对象的变量名
  234. }
  235. free(vars);//释放资源
  236. }];
  237. [cache setObject:keys forKey:cacheKey];
  238. return keys;
  239. }
  240. /**
  241. 抽取封装条件数组处理函数
  242. */
  243. +(NSArray*)where:(NSArray*)where{
  244. NSMutableArray* results = [NSMutableArray array];
  245. NSMutableString* SQL = [NSMutableString string];
  246. if(!(where.count%3)){
  247. [SQL appendString:@" where "];
  248. for(int i=0;i<where.count;i+=3){
  249. [SQL appendFormat:@"%@%@%@?",BG,where[i],where[i+1]];
  250. if (i != (where.count-3)) {
  251. [SQL appendString:@" and "];
  252. }
  253. }
  254. }else{
  255. //HLog(@"条件数组错误!");
  256. NSAssert(NO,@"条件数组错误!");
  257. }
  258. NSMutableArray* wheres = [NSMutableArray array];
  259. for(int i=0;i<where.count;i+=3){
  260. [wheres addObject:where[i+2]];
  261. }
  262. [results addObject:SQL];
  263. [results addObject:wheres];
  264. return results;
  265. }
  266. /**
  267. 封装like语句获取函数
  268. */
  269. +(NSString*)getLikeWithKeyPathAndValues:(NSArray* _Nonnull)keyPathValues where:(BOOL)where{
  270. NSAssert(keyPathValues,@"集合不能为空!");
  271. NSAssert(!(keyPathValues.count%3),@"集合格式错误!");
  272. NSMutableArray* keys = [NSMutableArray array];
  273. NSMutableArray* values = [NSMutableArray array];
  274. NSMutableArray* relations = [NSMutableArray array];
  275. for(int i=0;i<keyPathValues.count;i+=3){
  276. [keys addObject:keyPathValues[i]];
  277. [relations addObject:keyPathValues[i+1]];
  278. [values addObject:keyPathValues[i+2]];
  279. }
  280. NSMutableString* likeM = [NSMutableString string];
  281. !where?:[likeM appendString:@" where "];
  282. NSInteger keysCount = keys.count;
  283. for(int i=0;i<keysCount;i++){
  284. BOOL likeOr = NO;
  285. NSString* keyPath = keys[i];
  286. id value = values[i];
  287. NSAssert([keyPath containsString:@"."], @"keyPath错误,正确形式如: user.stident.name");
  288. NSArray* keypaths = [keyPath componentsSeparatedByString:@"."];
  289. NSMutableString* keyPathParam = [NSMutableString string];
  290. for(int i=1;i<keypaths.count;i++){
  291. i!=1?:[keyPathParam appendString:@"%"];
  292. [keyPathParam appendFormat:@"%@",keypaths[i]];
  293. [keyPathParam appendString:@"%"];
  294. }
  295. //[keyPathParam appendFormat:@"%@",value];
  296. if ([relations[i] isEqualToString:bg_contains]){//包含关系
  297. if(![value isKindOfClass:[NSString class]]){
  298. NSAssert(NO, @"非字符串不能设置包含关系!");
  299. }
  300. [keyPathParam appendFormat:@"%@",value];
  301. [keyPathParam appendString:@"%"];
  302. }else{
  303. if([value isKindOfClass:[NSString class]]){
  304. [keyPathParam appendFormat:@"\"%@",value];
  305. }else{
  306. [keyPathParam appendFormat:@": %@",value];
  307. }
  308. if(keypaths.count<=2){
  309. if([value isKindOfClass:[NSString class]]){
  310. [keyPathParam appendString:@"\\%"];
  311. }else{
  312. [keyPathParam appendString:@",%"];
  313. likeOr = YES;
  314. }
  315. }else{
  316. if([value isKindOfClass:[NSString class]]){
  317. [keyPathParam appendString:@"\\%"];
  318. }else{
  319. [keyPathParam appendString:@",%"];
  320. likeOr = YES;
  321. }
  322. }
  323. }
  324. if(likeOr){
  325. if(keypaths.count<=2){
  326. [likeM appendFormat:@"((%@%@ like '%@') or (%@%@ like '%@'))",BG,keypaths[0],keyPathParam,BG,keypaths[0],[keyPathParam stringByReplacingOccurrencesOfString:@"," withString:@"\n}"]];
  327. }else{
  328. [likeM appendFormat:@"((%@%@ like '%@') or (%@%@ like '%@'))",BG,keypaths[0],keyPathParam,BG,keypaths[0],[keyPathParam stringByReplacingOccurrencesOfString:@"," withString:@"\\"]];
  329. }
  330. }else{
  331. [likeM appendFormat:@"%@%@ like '%@'",BG,keypaths[0],keyPathParam];
  332. }
  333. if(i != (keys.count-1)){
  334. [likeM appendString:@" and "];
  335. }
  336. }
  337. return likeM;
  338. }
  339. /**
  340. 判断是不是 "唯一约束" 字段.
  341. */
  342. +(BOOL)isUniqueKey:(NSString*)uniqueKey with:(NSString*)param{
  343. NSArray* array = [param componentsSeparatedByString:@"*"];
  344. NSString* key = array[0];
  345. return [uniqueKey isEqualToString:key];
  346. }
  347. /**
  348. 判断并获取字段类型
  349. */
  350. +(NSString*)keyAndType:(NSString*)param{
  351. NSArray* array = [param componentsSeparatedByString:@"*"];
  352. NSString* key = array[0];
  353. NSString* type = array[1];
  354. NSString* SqlType;
  355. type = [self getSqlType:type];
  356. if ([SqlText isEqualToString:type]) {
  357. SqlType = SqlText;
  358. }else if ([SqlReal isEqualToString:type]){
  359. SqlType = SqlReal;
  360. }else if ([SqlInteger isEqualToString:type]){
  361. SqlType = SqlInteger;
  362. }else{
  363. NSAssert(NO,@"没有找到匹配的类型!");
  364. }
  365. //设置列名(BG_ + 属性名),加BG_是为了防止和数据库关键字发生冲突.
  366. return [NSString stringWithFormat:@"%@ %@",[NSString stringWithFormat:@"%@%@",BG,key],SqlType];
  367. }
  368. +(NSString*)getSqlType:(NSString*)type{
  369. if([type isEqualToString:@"i"]||[type isEqualToString:@"I"]||
  370. [type isEqualToString:@"s"]||[type isEqualToString:@"S"]||
  371. [type isEqualToString:@"q"]||[type isEqualToString:@"Q"]||
  372. [type isEqualToString:@"b"]||[type isEqualToString:@"B"]||
  373. [type isEqualToString:@"c"]||[type isEqualToString:@"C"]|
  374. [type isEqualToString:@"l"]||[type isEqualToString:@"L"]) {
  375. return SqlInteger;
  376. }else if([type isEqualToString:@"f"]||[type isEqualToString:@"F"]||
  377. [type isEqualToString:@"d"]||[type isEqualToString:@"D"]){
  378. return SqlReal;
  379. }else{
  380. return SqlText;
  381. }
  382. }
  383. //对象转json字符
  384. +(NSString *)jsonStringWithObject:(id)object{
  385. NSMutableDictionary* keyValueDict = [NSMutableDictionary dictionary];
  386. NSArray* keyAndTypes = [BGTool getClassIvarList:[object class] Object:object onlyKey:NO];
  387. //忽略属性
  388. NSArray* ignoreKeys = [BGTool executeSelector:bg_ignoreKeysSelector forClass:[object class]];
  389. for(NSString* keyAndType in keyAndTypes){
  390. NSArray* arr = [keyAndType componentsSeparatedByString:@"*"];
  391. NSString* propertyName = arr[0];
  392. NSString* propertyType = arr[1];
  393. if([ignoreKeys containsObject:propertyName])continue;
  394. if(![propertyName isEqualToString:bg_primaryKey]){
  395. id propertyValue = [object valueForKey:propertyName];
  396. if (propertyValue){
  397. id Value = [self getSqlValue:propertyValue type:propertyType encode:YES];
  398. keyValueDict[propertyName] = Value;
  399. }
  400. }
  401. }
  402. return [self dataToJson:keyValueDict];
  403. }
  404. //根据value类型返回用于数组插入数据库的NSDictionary
  405. +(NSDictionary*)dictionaryForArrayInsert:(id)value{
  406. if ([value isKindOfClass:[NSArray class]]){
  407. return @{BGArray:[self jsonStringWithArray:value]};
  408. }else if ([value isKindOfClass:[NSSet class]]){
  409. return @{BGSet:[self jsonStringWithArray:value]};
  410. }else if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]){
  411. return @{BGValue:value};
  412. }else if([value isKindOfClass:[NSData class]]){
  413. NSData* data = value;
  414. NSNumber* maxLength = MaxData;
  415. NSAssert(data.length<maxLength.integerValue,@"最大存储限制为100M");
  416. return @{BGData:[value base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]};
  417. }else if ([value isKindOfClass:[NSDictionary class]]){
  418. return @{BGDictionary:[self jsonStringWithDictionary:value]};
  419. }else if ([value isKindOfClass:[NSMapTable class]]){
  420. return @{BGMapTable:[self jsonStringWithMapTable:value]};
  421. }else if([value isKindOfClass:[NSHashTable class]]){
  422. return @{BGHashTable:[self jsonStringWithNSHashTable:value]};
  423. }else{
  424. NSString* modelKey = [NSString stringWithFormat:@"%@*%@",BGModel,NSStringFromClass([value class])];
  425. return @{modelKey:[self jsonStringWithObject:value]};
  426. }
  427. }
  428. //NSArray,NSSet转json字符
  429. +(NSString*)jsonStringWithArray:(id)array{
  430. if ([NSJSONSerialization isValidJSONObject:array]) {
  431. return [self dataToJson:array];
  432. }else{
  433. NSMutableArray* arrM = [NSMutableArray array];
  434. for(id value in array){
  435. [arrM addObject:[self dictionaryForArrayInsert:value]];
  436. }
  437. return [self dataToJson:arrM];
  438. }
  439. }
  440. //根据value类型返回用于字典插入数据库的NSDictionary
  441. +(NSDictionary*)dictionaryForDictionaryInsert:(id)value{
  442. if ([value isKindOfClass:[NSArray class]]){
  443. return @{BGArray:[self jsonStringWithArray:value]};
  444. }else if ([value isKindOfClass:[NSSet class]]){
  445. return @{BGSet:[self jsonStringWithArray:value]};
  446. }else if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]){
  447. return @{BGValue:value};
  448. }else if([value isKindOfClass:[NSData class]]){
  449. NSData* data = value;
  450. NSNumber* maxLength = MaxData;
  451. NSAssert(data.length<maxLength.integerValue,@"最大存储限制为100M");
  452. return @{BGData:[value base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]};
  453. }else if ([value isKindOfClass:[NSDictionary class]]){
  454. return @{BGDictionary:[self jsonStringWithDictionary:value]};
  455. }else if ([value isKindOfClass:[NSMapTable class]]){
  456. return @{BGMapTable:[self jsonStringWithMapTable:value]};
  457. }else if ([value isKindOfClass:[NSHashTable class]]){
  458. return @{BGHashTable:[self jsonStringWithNSHashTable:value]};
  459. }else{
  460. NSString* modelKey = [NSString stringWithFormat:@"%@*%@",BGModel,NSStringFromClass([value class])];
  461. return @{modelKey:[self jsonStringWithObject:value]};
  462. }
  463. }
  464. //字典转json字符串.
  465. +(NSString*)jsonStringWithDictionary:(NSDictionary*)dictionary{
  466. if ([NSJSONSerialization isValidJSONObject:dictionary]) {
  467. return [self dataToJson:dictionary];
  468. }else{
  469. NSMutableDictionary* dictM = [NSMutableDictionary dictionary];
  470. for(NSString* key in dictionary.allKeys){
  471. dictM[key] = [self dictionaryForDictionaryInsert:dictionary[key]];
  472. }
  473. return [self dataToJson:dictM];
  474. }
  475. }
  476. //NSMapTable转json字符串.
  477. +(NSString*)jsonStringWithMapTable:(NSMapTable*)mapTable{
  478. NSMutableDictionary* dictM = [NSMutableDictionary dictionary];
  479. NSArray* objects = mapTable.objectEnumerator.allObjects;
  480. NSArray* keys = mapTable.keyEnumerator.allObjects;
  481. for(int i=0;i<objects.count;i++){
  482. NSString* key = keys[i];
  483. id object = objects[i];
  484. dictM[key] = [self dictionaryForDictionaryInsert:object];
  485. }
  486. return [self dataToJson:dictM];
  487. }
  488. //NSHashTable转json字符串.
  489. +(NSString*)jsonStringWithNSHashTable:(NSHashTable*)hashTable{
  490. NSMutableArray* arrM = [NSMutableArray array];
  491. NSArray* values = hashTable.objectEnumerator.allObjects;
  492. for(id value in values){
  493. [arrM addObject:[self dictionaryForArrayInsert:value]];
  494. }
  495. return [self dataToJson:arrM];
  496. }
  497. //NSDate转字符串,格式: yyyy-MM-dd HH:mm:ss
  498. +(NSString*)stringWithDate:(NSDate*)date{
  499. NSDateFormatter* formatter = [NSDateFormatter new];
  500. formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
  501. return [formatter stringFromDate:date];
  502. }
  503. //跟value和数据类型type 和编解码标志 返回编码插入数据库的值,或解码数据库的值.
  504. +(id)getSqlValue:(id)value type:(NSString*)type encode:(BOOL)encode{
  505. if(!value || [value isKindOfClass:[NSNull class]])return nil;
  506. if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"String"]){
  507. if([type containsString:@"AttributedString"]){//处理富文本.
  508. if(encode) {
  509. return [[NSKeyedArchiver archivedDataWithRootObject:value] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  510. }else{
  511. NSData* data = [[NSData alloc] initWithBase64EncodedString:value options:NSDataBase64DecodingIgnoreUnknownCharacters];
  512. return [NSKeyedUnarchiver unarchiveObjectWithData:data];
  513. }
  514. }else{
  515. return value;
  516. }
  517. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"Number"]){
  518. if(encode) {
  519. return [NSString stringWithFormat:@"%@",value];
  520. }else{
  521. return [[NSNumberFormatter new] numberFromString:value];
  522. }
  523. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"Array"]){
  524. if(encode){
  525. return [self jsonStringWithArray:value];
  526. }else{
  527. return [self arrayFromJsonString:value];
  528. }
  529. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"Dictionary"]){
  530. if(encode){
  531. return [self jsonStringWithDictionary:value];
  532. }else{
  533. return [self dictionaryFromJsonString:value];
  534. }
  535. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"Set"]){
  536. if(encode){
  537. return [self jsonStringWithArray:value];
  538. }else{
  539. return [self arrayFromJsonString:value];
  540. }
  541. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"Data"]){
  542. if(encode){
  543. NSData* data = value;
  544. NSNumber* maxLength = MaxData;
  545. NSAssert(data.length<maxLength.integerValue,@"最大存储限制为100M");
  546. return [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  547. }else{
  548. return [[NSData alloc] initWithBase64EncodedString:value options:NSDataBase64DecodingIgnoreUnknownCharacters];
  549. }
  550. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"MapTable"]){
  551. if(encode){
  552. return [self jsonStringWithMapTable:value];
  553. }else{
  554. return [self mapTableFromJsonString:value];
  555. }
  556. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"HashTable"]){
  557. if(encode){
  558. return [self jsonStringWithNSHashTable:value];
  559. }else{
  560. return [self hashTableFromJsonString:value];
  561. }
  562. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"Date"]){
  563. if(encode){
  564. return [self stringWithDate:value];
  565. }else{
  566. return [self dateFromString:value];
  567. }
  568. }else if(([type hasPrefix:bg_typeHead_NS]||[type hasPrefix:bg_typeHead__NS])&&[type containsString:@"URL"]){
  569. if(encode){
  570. return [value absoluteString];
  571. }else{
  572. return [NSURL URLWithString:value];
  573. }
  574. }else if(([type hasPrefix:bg_typeHead_UI]||[type hasPrefix:bg_typeHead__UI])&&[type containsString:@"Image"]){
  575. if(encode){
  576. NSData* data = UIImageJPEGRepresentation(value, 1);
  577. NSNumber* maxLength = MaxData;
  578. NSAssert(data.length<maxLength.integerValue,@"最大存储限制为100M");
  579. return [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  580. }else{
  581. return [UIImage imageWithData:[[NSData alloc] initWithBase64EncodedString:value options:NSDataBase64DecodingIgnoreUnknownCharacters]];
  582. }
  583. }else if(([type hasPrefix:bg_typeHead_UI]||[type hasPrefix:bg_typeHead__UI])&&[type containsString:@"Color"]){
  584. if(encode){
  585. CGFloat r, g, b, a;
  586. [value getRed:&r green:&g blue:&b alpha:&a];
  587. return [NSString stringWithFormat:@"%.3f,%.3f,%.3f,%.3f", r, g, b, a];
  588. }else{
  589. NSArray<NSString*>* arr = [value componentsSeparatedByString:@","];
  590. return [UIColor colorWithRed:arr[0].floatValue green:arr[1].floatValue blue:arr[2].floatValue alpha:arr[3].floatValue];
  591. }
  592. }else if ([type containsString:@"NSRange"]){
  593. if(encode){
  594. return NSStringFromRange([value rangeValue]);
  595. }else{
  596. return [NSValue valueWithRange:NSRangeFromString(value)];
  597. }
  598. }else if ([type containsString:@"CGRect"]&&[type containsString:@"CGPoint"]&&[type containsString:@"CGSize"]){
  599. if(encode){
  600. return NSStringFromCGRect([value CGRectValue]);
  601. }else{
  602. return [NSValue valueWithCGRect:CGRectFromString(value)];
  603. }
  604. }else if (![type containsString:@"CGRect"]&&[type containsString:@"CGPoint"]&&![type containsString:@"CGSize"]){
  605. if(encode){
  606. return NSStringFromCGPoint([value CGPointValue]);
  607. }else{
  608. return [NSValue valueWithCGPoint:CGPointFromString(value)];
  609. }
  610. }else if (![type containsString:@"CGRect"]&&![type containsString:@"CGPoint"]&&[type containsString:@"CGSize"]){
  611. if(encode){
  612. return NSStringFromCGSize([value CGSizeValue]);
  613. }else{
  614. return [NSValue valueWithCGSize:CGSizeFromString(value)];
  615. }
  616. }else if([type isEqualToString:@"i"]||[type isEqualToString:@"I"]||
  617. [type isEqualToString:@"s"]||[type isEqualToString:@"S"]||
  618. [type isEqualToString:@"q"]||[type isEqualToString:@"Q"]||
  619. [type isEqualToString:@"b"]||[type isEqualToString:@"B"]||
  620. [type isEqualToString:@"c"]||[type isEqualToString:@"C"]||
  621. [type isEqualToString:@"l"]||[type isEqualToString:@"L"]){
  622. return value;
  623. }else if([type isEqualToString:@"f"]||[type isEqualToString:@"F"]||
  624. [type isEqualToString:@"d"]||[type isEqualToString:@"D"]){
  625. return value;
  626. }else{
  627. if(encode){
  628. NSBundle *bundle = [NSBundle bundleForClass:[value class]];
  629. if(bundle == [NSBundle mainBundle]){//自定义的类
  630. return [self jsonStringWithArray:@[value]];
  631. }else{//特殊类型
  632. return [[NSKeyedArchiver archivedDataWithRootObject:value] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  633. }
  634. }else{
  635. if([value containsString:BGModel]){//自定义的类
  636. return [self arrayFromJsonString:value].firstObject;
  637. }else{//特殊类型
  638. NSData* data = [[NSData alloc] initWithBase64EncodedString:value options:NSDataBase64DecodingIgnoreUnknownCharacters];
  639. return [NSKeyedUnarchiver unarchiveObjectWithData:data];
  640. }
  641. }
  642. }
  643. }
  644. /**
  645. 根据传入的对象获取表名.
  646. */
  647. +(NSString *)getTableNameWithObject:(id)object{
  648. NSString* tablename = [object valueForKey:bg_tableNameKey];
  649. if(tablename == nil) {
  650. tablename = NSStringFromClass([object class]);
  651. }
  652. return tablename;
  653. }
  654. /**
  655. 存储转换用的字典转化成对象处理函数.
  656. */
  657. +(id)objectFromJsonStringWithTableName:(NSString* _Nonnull)tablename class:(__unsafe_unretained _Nonnull Class)cla valueDict:(NSDictionary*)valueDict{
  658. id object = [cla new];
  659. NSMutableArray* valueDictKeys = [NSMutableArray arrayWithArray:valueDict.allKeys];
  660. NSMutableArray* keyAndTypes = [NSMutableArray arrayWithArray:[self getClassIvarList:cla Object:nil onlyKey:NO]];
  661. for(int i=0;i<valueDictKeys.count;i++){
  662. NSString* sqlKey = valueDictKeys[i];
  663. NSString* tempSqlKey = sqlKey;
  664. if([sqlKey containsString:BG]){
  665. tempSqlKey = [sqlKey stringByReplacingOccurrencesOfString:BG withString:@""];
  666. }
  667. for(NSString* keyAndType in keyAndTypes){
  668. NSArray* arrKT = [keyAndType componentsSeparatedByString:@"*"];
  669. NSString* key = [arrKT firstObject];
  670. NSString* type = [arrKT lastObject];
  671. if ([tempSqlKey isEqualToString:key]){
  672. id tempValue = valueDict[sqlKey];
  673. id ivarValue = [self getSqlValue:tempValue type:type encode:NO];
  674. !ivarValue?:[object setValue:ivarValue forKey:key];
  675. [keyAndTypes removeObject:keyAndType];
  676. [valueDictKeys removeObjectAtIndex:i];
  677. i--;
  678. break;//匹配处理完后跳出内循环.
  679. }
  680. }
  681. }
  682. [object setValue:tablename forKey:bg_tableNameKey];
  683. return object;
  684. }
  685. /**
  686. 字典或json格式字符转模型用的处理函数.
  687. */
  688. +(id)bg_objectWithClass:(__unsafe_unretained _Nonnull Class)cla value:(id)value{
  689. if(value == nil)return nil;
  690. NSMutableDictionary* dataDict;
  691. id object = [cla new];
  692. if ([value isKindOfClass:[NSString class]]){
  693. NSAssert([NSJSONSerialization isValidJSONObject:value],@"json数据格式错误!");
  694. dataDict = [[NSMutableDictionary alloc] initWithDictionary:[self jsonWithString:value] copyItems:YES];
  695. }else if ([value isKindOfClass:[NSDictionary class]]){
  696. dataDict = [[NSMutableDictionary alloc] initWithDictionary:value copyItems:YES];
  697. }else{
  698. NSAssert(NO,@"数据格式错误!, 只能转换字典或json格式数据.");
  699. }
  700. NSDictionary* const objectClaInArr = [BGTool executeSelector:NSSelectorFromString(@"bg_objectClassInArray") forClass:[object class]];
  701. NSDictionary* const objectClaForCustom = [BGTool executeSelector:NSSelectorFromString(@"bg_objectClassForCustom") forClass:[object class]];
  702. NSDictionary* const bg_replacedKeyFromPropertyNameDict = [BGTool executeSelector:NSSelectorFromString(@"bg_replacedKeyFromPropertyName") forClass:[object class]];
  703. NSArray* const claKeys = [self getClassIvarList:cla Object:nil onlyKey:YES];
  704. //遍历自定义变量集合信息.
  705. !objectClaForCustom?:[objectClaForCustom enumerateKeysAndObjectsUsingBlock:^(id _Nonnull customKey, id _Nonnull customObj, BOOL * _Nonnull stop) {
  706. if ([customKey containsString:@"."]){
  707. NSArray* keyPaths = [customKey componentsSeparatedByString:@"."];
  708. id value = [dataDict valueForKeyPath:customKey];
  709. dataDict[keyPaths.lastObject] = value;
  710. if(![objectClaForCustom.allKeys containsObject:keyPaths.firstObject]){
  711. [dataDict removeObjectForKey:keyPaths.firstObject];
  712. }
  713. }
  714. }];
  715. //处理要替换的key和属性名.
  716. if(bg_replacedKeyFromPropertyNameDict && bg_replacedKeyFromPropertyNameDict.count){
  717. [bg_replacedKeyFromPropertyNameDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  718. if([dataDict.allKeys containsObject:key]){
  719. dataDict[obj] = dataDict[key];
  720. [dataDict removeObjectForKey:key];
  721. }
  722. }];
  723. }
  724. [dataDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull dataDictObj, BOOL * _Nonnull stop) {
  725. for(NSString* claKey in claKeys){
  726. if ([key isEqualToString:claKey]){
  727. __block id ArrObject = dataDictObj;
  728. //遍历自定义变量数组集合信息.
  729. !objectClaInArr?:[objectClaInArr enumerateKeysAndObjectsUsingBlock:^(id _Nonnull Arrkey, id _Nonnull ArrObjCla, BOOL * _Nonnull stop){
  730. if([key isEqualToString:Arrkey]){
  731. NSMutableArray* ArrObjects = [NSMutableArray array];
  732. for(NSDictionary* ArrObj in dataDictObj){
  733. id obj = [self bg_objectWithClass:ArrObjCla value:ArrObj];
  734. [ArrObjects addObject:obj];
  735. }
  736. ArrObject = ArrObjects;
  737. *stop = YES;
  738. }
  739. }];
  740. //遍历自定义变量集合信息.
  741. !objectClaForCustom?:[objectClaForCustom enumerateKeysAndObjectsUsingBlock:^(id _Nonnull customKey, id _Nonnull customObj, BOOL * _Nonnull stop) {
  742. NSString* tempKey = customKey;
  743. if ([customKey containsString:@"."]){
  744. tempKey = [customKey componentsSeparatedByString:@"."].lastObject;
  745. }
  746. if([key isEqualToString:tempKey]){
  747. ArrObject = [self bg_objectWithClass:customObj value:[dataDict valueForKey:tempKey]];
  748. *stop = YES;
  749. }
  750. }];
  751. [object setValue:ArrObject forKey:key];
  752. break;//匹配到了就跳出循环.
  753. }
  754. }
  755. }];
  756. return object;
  757. }
  758. /**
  759. 模型转字典.
  760. */
  761. +(NSMutableDictionary*)bg_keyValuesWithObject:(id)object ignoredKeys:(NSArray*)ignoredKeys{
  762. NSMutableArray<NSString*>* keys = [[NSMutableArray alloc] initWithArray:[self getClassIvarList:[object class] Object:nil onlyKey:YES]];
  763. if (ignoredKeys) {
  764. [keys removeObjectsInArray:ignoredKeys];
  765. }
  766. NSDictionary* const objectClaInArr = [BGTool executeSelector:NSSelectorFromString(@"bg_objectClassInArray") forClass:[object class]];
  767. NSDictionary* const objectClaForCustom = [BGTool executeSelector:NSSelectorFromString(@"bg_dictForCustomClass") forClass:[object class]];
  768. NSMutableDictionary* dictM = [NSMutableDictionary dictionary];
  769. [keys enumerateObjectsUsingBlock:^(NSString * _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
  770. __block id value = [object valueForKey:key];
  771. //遍历自定义变量数组集合信息.
  772. !objectClaInArr?:[objectClaInArr enumerateKeysAndObjectsUsingBlock:^(id _Nonnull Arrkey, id _Nonnull ArrObjCla, BOOL * _Nonnull stop){
  773. if([key isEqualToString:Arrkey]){
  774. NSMutableArray* ArrObjects = [NSMutableArray array];
  775. for(id arrObj in value){
  776. id dictObj = [self bg_keyValuesWithObject:arrObj ignoredKeys:nil];
  777. [ArrObjects addObject:dictObj];
  778. }
  779. value = ArrObjects;
  780. *stop = YES;
  781. }
  782. }];
  783. //遍历自定义变量集合信息.
  784. !objectClaForCustom?:[objectClaForCustom enumerateKeysAndObjectsUsingBlock:^(NSString* _Nonnull customKey, id _Nonnull customObj, BOOL * _Nonnull stop) {
  785. if([key isEqualToString:customKey]){
  786. value = [self bg_keyValuesWithObject:[object valueForKey:customKey] ignoredKeys:nil];
  787. *stop = YES;
  788. }
  789. }];
  790. //存到集合里.
  791. !value?:[dictM setValue:value forKey:key];
  792. }];
  793. return dictM;
  794. }
  795. //根据NSDictionary转换从数据库读取回来的数组数据
  796. +(id)valueForArrayRead:(NSDictionary*)dictionary{
  797. NSString* key = dictionary.allKeys.firstObject;
  798. if ([key isEqualToString:BGValue]) {
  799. return dictionary[key];
  800. }else if ([key isEqualToString:BGData]){
  801. return [[NSData alloc] initWithBase64EncodedString:dictionary[key] options:NSDataBase64DecodingIgnoreUnknownCharacters];
  802. }else if([key isEqualToString:BGSet]){
  803. return [self arrayFromJsonString:dictionary[key]];
  804. }else if([key isEqualToString:BGArray]){
  805. return [self arrayFromJsonString:dictionary[key]];
  806. }else if ([key isEqualToString:BGDictionary]){
  807. return [self dictionaryFromJsonString:dictionary[key]];
  808. }else if ([key containsString:BGModel]){
  809. NSString* claName = [key componentsSeparatedByString:@"*"].lastObject;
  810. NSDictionary* valueDict = [self jsonWithString:dictionary[key]];
  811. id object = [self objectFromJsonStringWithTableName:claName class:NSClassFromString(claName) valueDict:valueDict];
  812. return object;
  813. }else{
  814. NSAssert(NO,@"没有找到匹配的解析类型");
  815. return nil;
  816. }
  817. }
  818. //json字符串转NSArray
  819. +(NSArray*)arrayFromJsonString:(NSString*)jsonString{
  820. if(!jsonString || [jsonString isKindOfClass:[NSNull class]])return nil;
  821. if([jsonString containsString:BGModel] || [jsonString containsString:BGData]){
  822. NSMutableArray* arrM = [NSMutableArray array];
  823. NSArray* array = [self jsonWithString:jsonString];
  824. for(NSDictionary* dict in array){
  825. [arrM addObject:[self valueForArrayRead:dict]];
  826. }
  827. return arrM;
  828. }else{
  829. return [self jsonWithString:jsonString];
  830. }
  831. }
  832. //根据NSDictionary转换从数据库读取回来的字典数据
  833. +(id)valueForDictionaryRead:(NSDictionary*)dictDest{
  834. NSString* keyDest = dictDest.allKeys.firstObject;
  835. if([keyDest isEqualToString:BGValue]){
  836. return dictDest[keyDest];
  837. }else if ([keyDest isEqualToString:BGData]){
  838. return [[NSData alloc] initWithBase64EncodedString:dictDest[keyDest] options:NSDataBase64DecodingIgnoreUnknownCharacters];
  839. }else if([keyDest isEqualToString:BGSet]){
  840. return [self arrayFromJsonString:dictDest[keyDest]];
  841. }else if([keyDest isEqualToString:BGArray]){
  842. return [self arrayFromJsonString:dictDest[keyDest]];
  843. }else if([keyDest isEqualToString:BGDictionary]){
  844. return [self dictionaryFromJsonString:dictDest[keyDest]];
  845. }else if([keyDest containsString:BGModel]){
  846. NSString* claName = [keyDest componentsSeparatedByString:@"*"].lastObject;
  847. NSDictionary* valueDict = [self jsonWithString:dictDest[keyDest]];
  848. return [self objectFromJsonStringWithTableName:claName class:NSClassFromString(claName) valueDict:valueDict];
  849. }else{
  850. NSAssert(NO,@"没有找到匹配的解析类型");
  851. return nil;
  852. }
  853. }
  854. //json字符串转NSDictionary
  855. +(NSDictionary*)dictionaryFromJsonString:(NSString*)jsonString{
  856. if(!jsonString || [jsonString isKindOfClass:[NSNull class]])return nil;
  857. if([jsonString containsString:BGModel] || [jsonString containsString:BGData]){
  858. NSMutableDictionary* dictM = [NSMutableDictionary dictionary];
  859. NSDictionary* dictSrc = [self jsonWithString:jsonString];
  860. for(NSString* keySrc in dictSrc.allKeys){
  861. NSDictionary* dictDest = dictSrc[keySrc];
  862. dictM[keySrc]= [self valueForDictionaryRead:dictDest];
  863. }
  864. return dictM;
  865. }else{
  866. return [self jsonWithString:jsonString];
  867. }
  868. }
  869. //json字符串转NSMapTable
  870. +(NSMapTable*)mapTableFromJsonString:(NSString*)jsonString{
  871. if(!jsonString || [jsonString isKindOfClass:[NSNull class]])return nil;
  872. NSDictionary* dict = [self jsonWithString:jsonString];
  873. NSMapTable* mapTable = [NSMapTable new];
  874. for(NSString* key in dict.allKeys){
  875. id value = [self valueForDictionaryRead:dict[key]];
  876. [mapTable setObject:value forKey:key];
  877. }
  878. return mapTable;
  879. }
  880. //json字符串转NSHashTable
  881. +(NSHashTable*)hashTableFromJsonString:(NSString*)jsonString{
  882. if(!jsonString || [jsonString isKindOfClass:[NSNull class]])return nil;
  883. NSArray* arr = [self jsonWithString:jsonString];
  884. NSHashTable* hashTable = [NSHashTable new];
  885. for (id obj in arr) {
  886. id value = [self valueForArrayRead:obj];
  887. [hashTable addObject:value];
  888. }
  889. return hashTable;
  890. }
  891. //json字符串转NSDate
  892. +(NSDate*)dateFromString:(NSString*)jsonString{
  893. if(!jsonString || [jsonString isKindOfClass:[NSNull class]])return nil;
  894. NSDateFormatter *formatter = [NSDateFormatter new];
  895. formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
  896. NSDate *date = [formatter dateFromString:jsonString];
  897. return date;
  898. }
  899. //转换从数据库中读取出来的数据.
  900. +(NSArray*)tansformDataFromSqlDataWithTableName:(NSString*)tableName class:(__unsafe_unretained _Nonnull Class)cla array:(NSArray*)array{
  901. //如果传入的class为空,则直接以字典的形式返回.
  902. if(cla == nil){
  903. return array;
  904. }
  905. NSMutableArray* arrM = [NSMutableArray array];
  906. for(NSMutableDictionary* dict in array){
  907. //#warning 压缩深层嵌套模型数据量使用
  908. // NSString* depth_model_conditions = @"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
  909. // [dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  910. // if([obj isKindOfClass:[NSString class]] && ([obj containsString:@"+&"]||
  911. // [obj containsString:@"~-"]||[obj containsString:@"$#"]||[obj containsString:@"^*"])){
  912. // if ([obj containsString:BGModel]) {
  913. // obj = [obj stringByReplacingOccurrencesOfString:@"+&" withString:@"~-~-~-"];
  914. // obj = [obj stringByReplacingOccurrencesOfString:@"~-" withString:@"$#$#$#$#$#"];
  915. // obj = [obj stringByReplacingOccurrencesOfString:@"$#" withString:@"^*^*^*^*^*^*^*^*^*^*"];
  916. // dict[key] = [obj stringByReplacingOccurrencesOfString:@"^*" withString:depth_model_conditions];
  917. // }
  918. // }
  919. // }];
  920. id object = [BGTool objectFromJsonStringWithTableName:tableName class:cla valueDict:dict];
  921. [arrM addObject:object];
  922. }
  923. return arrM;
  924. }
  925. /**
  926. 判断类是否实现了某个类方法.
  927. */
  928. +(id)executeSelector:(SEL)selector forClass:(Class)cla{
  929. id obj = nil;
  930. if([cla respondsToSelector:selector]){
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  933. obj = [cla performSelector:selector];
  934. #pragma clang diagnostic pop
  935. }
  936. return obj;
  937. }
  938. /**
  939. 判断对象是否实现了某个方法.
  940. */
  941. +(id)executeSelector:(SEL)selector forObject:(id)object{
  942. id obj = nil;
  943. if([object respondsToSelector:selector]){
  944. #pragma clang diagnostic push
  945. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  946. obj = [object performSelector:selector];
  947. #pragma clang diagnostic pop
  948. }
  949. return obj;
  950. }
  951. /**
  952. 获取存储数据
  953. */
  954. +(NSMutableDictionary*)getDictWithObject:(id)object ignoredKeys:(NSArray* const)ignoredKeys{
  955. NSMutableDictionary* modelInfoDictM = [NSMutableDictionary dictionary];
  956. NSArray* keyAndTypes = [BGTool getClassIvarList:[object class] Object:object onlyKey:NO];
  957. for(NSString* keyAndType in keyAndTypes){
  958. NSArray* keyTypes = [keyAndType componentsSeparatedByString:@"*"];
  959. NSString* propertyName = keyTypes[0];
  960. NSString* propertyType = keyTypes[1];
  961. if(![ignoredKeys containsObject:propertyName]){
  962. //数据库表列名(BG_ + 属性名),加BG_是为了防止和数据库关键字发生冲突.
  963. NSString* sqlColumnName = [NSString stringWithFormat:@"%@%@",BG,propertyName];
  964. id propertyValue;
  965. id sqlValue;
  966. //crateTime和updateTime两个额外字段单独处理.
  967. if([propertyName isEqualToString:bg_createTimeKey] ||
  968. [propertyName isEqualToString:bg_updateTimeKey]){
  969. propertyValue = [BGTool stringWithDate:[NSDate new]];
  970. }else{
  971. propertyValue = [object valueForKey:propertyName];
  972. }
  973. if(propertyValue){
  974. //列值
  975. sqlValue = [BGTool getSqlValue:propertyValue type:propertyType encode:YES];
  976. modelInfoDictM[sqlColumnName] = sqlValue;
  977. }
  978. }
  979. }
  980. NSAssert(modelInfoDictM.allKeys.count,@"对象变量数据为空,不能存储!");
  981. return modelInfoDictM;
  982. }
  983. /**
  984. 根据对象获取要更新或插入的字典.
  985. */
  986. +(NSDictionary* _Nonnull)getDictWithObject:(id _Nonnull)object ignoredKeys:(NSArray* const _Nullable)ignoredKeys filtModelInfoType:(bg_getModelInfoType)filtModelInfoType{
  987. //获取存到数据库的数据.
  988. NSMutableDictionary* valueDict = [self getDictWithObject:object ignoredKeys:ignoredKeys];
  989. if (filtModelInfoType == bg_ModelInfoSingleUpdate){//单条更新操作时,移除 创建时间和主键 字段不做更新
  990. [valueDict removeObjectForKey:bg_sqlKey(bg_createTimeKey)];
  991. //判断是否定义了“联合主键”.
  992. NSArray* unionPrimaryKeys = [BGTool executeSelector:bg_unionPrimaryKeysSelector forClass:[object class]];
  993. NSString* bg_id = bg_sqlKey(bg_primaryKey);
  994. if(unionPrimaryKeys.count == 0){
  995. if([valueDict.allKeys containsObject:bg_id]) {
  996. [valueDict removeObjectForKey:bg_id];
  997. }
  998. }else{
  999. if(![valueDict.allKeys containsObject:bg_id]) {
  1000. valueDict[bg_id] = @(1);//没有就预备放入
  1001. }
  1002. }
  1003. }else if(filtModelInfoType == bg_ModelInfoInsert){//插入时要移除主键,不然会出错.
  1004. //判断是否定义了“联合主键”.
  1005. NSArray* unionPrimaryKeys = [BGTool executeSelector:bg_unionPrimaryKeysSelector forClass:[object class]];
  1006. NSString* bg_id = bg_sqlKey(bg_primaryKey);
  1007. if(unionPrimaryKeys.count == 0){
  1008. if([valueDict.allKeys containsObject:bg_id]) {
  1009. [valueDict removeObjectForKey:bg_id];
  1010. }
  1011. }else{
  1012. if(![valueDict.allKeys containsObject:bg_id]) {
  1013. valueDict[bg_id] = @(1);//没有就预备放入
  1014. }
  1015. }
  1016. }else if(filtModelInfoType == bg_ModelInfoArrayUpdate){//批量更新操作时,移除 创建时间 字段不做更新
  1017. [valueDict removeObjectForKey:bg_sqlKey(bg_createTimeKey)];
  1018. }else;
  1019. //#warning 压缩深层嵌套模型数据量使用
  1020. // NSString* depth_model_conditions = @"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
  1021. // [valueDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  1022. // if([obj isKindOfClass:[NSString class]] && [obj containsString:depth_model_conditions]){
  1023. // if ([obj containsString:BGModel]) {
  1024. // obj = [obj stringByReplacingOccurrencesOfString:depth_model_conditions withString:@"^*"];
  1025. // obj = [obj stringByReplacingOccurrencesOfString:@"^*^*^*^*^*^*^*^*^*^*" withString:@"$#"];
  1026. // obj = [obj stringByReplacingOccurrencesOfString:@"$#$#$#$#$#" withString:@"~-"];
  1027. // valueDict[key] = [obj stringByReplacingOccurrencesOfString:@"~-~-~-" withString:@"+&"];
  1028. // }
  1029. // }
  1030. // }];
  1031. return valueDict;
  1032. }
  1033. /**
  1034. 过滤建表的key.
  1035. */
  1036. +(NSArray*)bg_filtCreateKeys:(NSArray*)bg_createkeys ignoredkeys:(NSArray*)bg_ignoredkeys{
  1037. NSMutableArray* createKeys = [NSMutableArray arrayWithArray:bg_createkeys];
  1038. NSMutableArray* ignoredKeys = [NSMutableArray arrayWithArray:bg_ignoredkeys];
  1039. //判断是否有需要忽略的key集合.
  1040. if (ignoredKeys.count){
  1041. for(__block int i=0;i<createKeys.count;i++){
  1042. if(ignoredKeys.count){
  1043. NSString* createKey = [createKeys[i] componentsSeparatedByString:@"*"][0];
  1044. [ignoredKeys enumerateObjectsUsingBlock:^(id _Nonnull ignoreKey, NSUInteger idx, BOOL * _Nonnull stop) {
  1045. if([createKey isEqualToString:ignoreKey]){
  1046. [createKeys removeObjectAtIndex:i];
  1047. [ignoredKeys removeObjectAtIndex:idx];
  1048. i--;
  1049. *stop = YES;
  1050. }
  1051. }];
  1052. }else{
  1053. break;
  1054. }
  1055. }
  1056. }
  1057. return createKeys;
  1058. }
  1059. /**
  1060. 如果表格不存在就新建.
  1061. */
  1062. +(BOOL)ifNotExistWillCreateTableWithObject:(id)object ignoredKeys:(NSArray* const)ignoredKeys{
  1063. //检查是否建立了跟对象相对应的数据表
  1064. NSString* tableName = [BGTool getTableNameWithObject:object];
  1065. //获取"唯一约束"字段名
  1066. NSArray* uniqueKeys = [BGTool executeSelector:bg_uniqueKeysSelector forClass:[object class]];
  1067. //获取“联合主键”字段名
  1068. NSArray* unionPrimaryKeys = [BGTool executeSelector:bg_unionPrimaryKeysSelector forClass:[object class]];
  1069. __block BOOL isExistTable;
  1070. [[BGDB shareManager] isExistWithTableName:tableName complete:^(BOOL isExist) {
  1071. if (!isExist){//如果不存在就新建
  1072. NSArray* createKeys = [self bg_filtCreateKeys:[BGTool getClassIvarList:[object class] Object:object onlyKey:NO] ignoredkeys:ignoredKeys];
  1073. [[BGDB shareManager] createTableWithTableName:tableName keys:createKeys unionPrimaryKeys:unionPrimaryKeys uniqueKeys:uniqueKeys complete:^(BOOL isSuccess) {
  1074. isExistTable = isSuccess;
  1075. }];
  1076. }
  1077. }];
  1078. return isExistTable;
  1079. }
  1080. /**
  1081. 整形判断
  1082. */
  1083. + (BOOL)isPureInt:(NSString *)string{
  1084. NSScanner* scan = [NSScanner scannerWithString:string];
  1085. int val;
  1086. return [scan scanInt:&val] && [scan isAtEnd];
  1087. }
  1088. /**
  1089. 浮点形判断
  1090. */
  1091. + (BOOL)isPureFloat:(NSString *)string{
  1092. NSScanner* scan = [NSScanner scannerWithString:string];
  1093. float val;
  1094. return [scan scanFloat:&val] && [scan isAtEnd];
  1095. }
  1096. +(BOOL)getBoolWithKey:(NSString*)key{
  1097. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1098. return [defaults boolForKey:key];
  1099. }
  1100. +(void)setBoolWithKey:(NSString*)key value:(BOOL)value{
  1101. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1102. [defaults setBool:value forKey:key];
  1103. [defaults synchronize];
  1104. }
  1105. +(NSString*)getStringWithKey:(NSString*)key{
  1106. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1107. return [defaults stringForKey:key];
  1108. }
  1109. +(void)setStringWithKey:(NSString*)key value:(NSString*)value{
  1110. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1111. [defaults setObject:value forKey:key];
  1112. [defaults synchronize];
  1113. }
  1114. +(NSInteger)getIntegerWithKey:(NSString*)key{
  1115. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1116. return [defaults integerForKey:key];
  1117. }
  1118. +(void)setIntegerWithKey:(NSString*)key value:(NSInteger)value{
  1119. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  1120. [defaults setInteger:value forKey:key];
  1121. [defaults synchronize];
  1122. }
  1123. @end