Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

增加字典数组转模型数组的方法 #253

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions YYModel/NSObject+YYModel.h 100644 → 100755
Expand Up @@ -102,6 +102,15 @@ NS_ASSUME_NONNULL_BEGIN
*/
+ (nullable instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary;


/**
Creates and returns a new instance of the receiver from an array containing key-value dictionary, automatic parsing multiple array, if contain anything else element except dictionary, method will return a uninitialized instance.

@param keyValueArray An array containing key-value dictionary mapped to the instance's properties.
@return A new array containing instance.
*/
+ (NSMutableArray *)yy_modelArrayWithKeyValueArray:(NSArray *)keyValueArray;

/**
Set the receiver's properties with a json object.

Expand Down
22 changes: 22 additions & 0 deletions YYModel/NSObject+YYModel.m 100644 → 100755
Expand Up @@ -1454,6 +1454,28 @@ + (instancetype)yy_modelWithJSON:(id)json {
return [self yy_modelWithDictionary:dic];
}

+ (NSMutableArray *)yy_modelArrayWithKeyValueArray:(NSArray *)keyValueArray {
if (!keyValueArray || keyValueArray == (id)kCFNull) return nil;
if (![keyValueArray isKindOfClass:[NSArray class]]) return nil;
NSMutableArray *modelArray = [NSMutableArray array];
return [self _yy_modelArrayWithRecurArray:keyValueArray modelArray:modelArray];;
}

+ (NSMutableArray *)_yy_modelArrayWithRecurArray:(NSArray *)array modelArray:(NSMutableArray *)modelArray {
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[NSArray class]]) {
NSMutableArray *array = [NSMutableArray array];
[modelArray addObject:[self _yy_modelArrayWithRecurArray:obj modelArray:array]];
} else {
if (![obj isKindOfClass:[NSDictionary class]]) {
obj = [NSDictionary dictionary];
}
[modelArray addObject:[self yy_modelWithDictionary:obj]];
}
}];
return modelArray;
}

+ (instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary {
if (!dictionary || dictionary == (id)kCFNull) return nil;
if (![dictionary isKindOfClass:[NSDictionary class]]) return nil;
Expand Down