// // MOUserListData.m // // Created by SuperCabbage on 2023/11/28 // Copyright (c) 2023 __MyCompanyName__. All rights reserved. // #import "MOUserListData.h" #import "MOUserBase.h" NSString *const kMOUserListDataUserBase = @"list"; @interface MOUserListData () - (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict; @end @implementation MOUserListData @synthesize userBase = _userBase; + (instancetype)modelObjectWithDictionary:(NSDictionary *)dict { return [[self alloc] initWithDictionary:dict]; } - (instancetype)initWithDictionary:(NSDictionary *)dict { self = [super init]; // This check serves to make sure that a non-NSDictionary object // passed into the model class doesn't break the parsing. if (self && [dict isKindOfClass:[NSDictionary class]]) { NSObject *receivedMOUserBase = [dict objectForKey:kMOUserListDataUserBase]; NSMutableArray *parsedMOUserBase = [NSMutableArray array]; if ([receivedMOUserBase isKindOfClass:[NSArray class]]) { for (NSDictionary *item in (NSArray *)receivedMOUserBase) { if ([item isKindOfClass:[NSDictionary class]]) { [parsedMOUserBase addObject:[MOUserBase modelObjectWithDictionary:item]]; } } } else if ([receivedMOUserBase isKindOfClass:[NSDictionary class]]) { [parsedMOUserBase addObject:[MOUserBase modelObjectWithDictionary:(NSDictionary *)receivedMOUserBase]]; } self.userBase = [NSArray arrayWithArray:parsedMOUserBase]; } return self; } - (NSDictionary *)dictionaryRepresentation { NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary]; NSMutableArray *tempArrayForUserBase = [NSMutableArray array]; for (NSObject *subArrayObject in self.userBase) { if ([subArrayObject respondsToSelector:@selector(dictionaryRepresentation)]) { // This class is a model object [tempArrayForUserBase addObject:[subArrayObject performSelector:@selector(dictionaryRepresentation)]]; } else { // Generic object [tempArrayForUserBase addObject:subArrayObject]; } } [mutableDict setValue:[NSArray arrayWithArray:tempArrayForUserBase] forKey:kMOUserListDataUserBase]; return [NSDictionary dictionaryWithDictionary:mutableDict]; } - (NSString *)description { return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]]; } #pragma mark - Helper Method - (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict { id object = [dict objectForKey:aKey]; return [object isEqual:[NSNull null]] ? nil : object; } #pragma mark - NSCoding Methods - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; self.userBase = [aDecoder decodeObjectForKey:kMOUserListDataUserBase]; return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_userBase forKey:kMOUserListDataUserBase]; } - (id)copyWithZone:(NSZone *)zone { MOUserListData *copy = [[MOUserListData alloc] init]; if (copy) { copy.userBase = [self.userBase copyWithZone:zone]; } return copy; } @end