1,使用 'MJExtension' 處理字典和模型。
注意:自定義類型中包含自定義類型,需要實現 + (NSDictionary *)mj_objectClassInArray
方法
@class Person;
@interface Group : NSObject
@property (nonatomic, strong) NSString *groupName;
@property (nonatomic, strong) NSArray<Person *> *members;
@property (nonatomic, strong) NSArray<Person *> *teachers;
@end
@implementation Group
+ (NSDictionary *)mj_objectClassInArray{
return @{
@"members": @"Person",
@"teachers": [Person class]
};
}
@end
2,YTKKeyValueStore 可以對系統類型的數據進行存儲,對于自定義類型,將自定義類型處理成Json數據再進行存儲即可。
#import <Foundation/Foundation.h>
#import "YTKKeyValueStore.h"
@interface YTKKeyValueStore (CustomObject)
/******** 自定義類型相關 *********************************************************/
/** 存儲自定義類型 */
- (void)putCustomObject:(id)object
withId:(NSString *)objectId
intoTable:(NSString *)tableName;
/** 存儲包含自定義類型的數組 */
- (void)putArrWithCustomClass:(Class)aclass
object:(id)object
withId:(NSString *)objectId
intoTable:(NSString *)tableName;
/** 獲取自定義類型的對象方法 */
- (id)getCustomClass:(Class)aclass
objectById:(NSString *)objectId
fromTable:(NSString *)tableName;
@end
@interface AGKeyValueManage : NSObject
+ (void)storeWithDBName:(NSString *)dbName tableName:(NSString *)tableName handle:(void (^)(YTKKeyValueStore *store, NSString *tableName))handle;
@end
#import "AGKeyValueManage.h"
#import "MJExtension.h"
@implementation YTKKeyValueStore (CustomObject)
- (void)putCustomObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName{
NSDictionary *dic = [object mj_keyValues];
[self putObject:dic withId:objectId intoTable:tableName];
}
/**
將包含自定義對象的數組轉成包含
*/
- (void)putArrWithCustomClass:(Class)aclass object:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName{
NSArray *dicArr = [aclass mj_keyValuesArrayWithObjectArray:object];
[self putObject:dicArr withId:objectId intoTable:tableName];
}
- (id)getCustomClass:(Class)aclass objectById:(NSString *)objectId fromTable:(NSString *)tableName{
id object = [self getObjectById:objectId fromTable:tableName];
id result;
if ([object isKindOfClass:[NSArray class]]) {
result = [aclass mj_objectArrayWithKeyValuesArray:object];
}
else{
result = [aclass mj_objectWithKeyValues:object];
}
return result;
}
@end
@implementation AGKeyValueManage
+ (void)storeWithDBName:(NSString *)dbName tableName:(NSString *)tableName handle:(void (^)(YTKKeyValueStore *store, NSString *tableName))handle{
if (!handle) {
return;
}
YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:dbName];
[store createTableWithName:tableName];
handle(store, tableName);
}
@end