// // MOEventData.m // // Created by SuperCabbage on 2024/1/31 // Copyright (c) 2024 __MyCompanyName__. All rights reserved. // #import "MOEventData.h" #import "MOEventList.h" NSString *const kMOEventDataEventList = @"list"; @interface MOEventData () - (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict; @end @implementation MOEventData @synthesize eventList = _eventList; + (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 *receivedMOEventList = [dict objectForKey:kMOEventDataEventList]; NSMutableArray *parsedMOEventList = [NSMutableArray array]; if ([receivedMOEventList isKindOfClass:[NSArray class]]) { for (NSDictionary *item in (NSArray *)receivedMOEventList) { if ([item isKindOfClass:[NSDictionary class]]) { [parsedMOEventList addObject:[MOEventList modelObjectWithDictionary:item]]; } } } else if ([receivedMOEventList isKindOfClass:[NSDictionary class]]) { [parsedMOEventList addObject:[MOEventList modelObjectWithDictionary:(NSDictionary *)receivedMOEventList]]; } self.eventList = [NSArray arrayWithArray:parsedMOEventList]; } return self; } - (NSDictionary *)dictionaryRepresentation { NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary]; NSMutableArray *tempArrayForEventList = [NSMutableArray array]; for (NSObject *subArrayObject in self.eventList) { if ([subArrayObject respondsToSelector:@selector(dictionaryRepresentation)]) { // This class is a model object [tempArrayForEventList addObject:[subArrayObject performSelector:@selector(dictionaryRepresentation)]]; } else { // Generic object [tempArrayForEventList addObject:subArrayObject]; } } [mutableDict setValue:[NSArray arrayWithArray:tempArrayForEventList] forKey:kMOEventDataEventList]; 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.eventList = [aDecoder decodeObjectForKey:kMOEventDataEventList]; return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_eventList forKey:kMOEventDataEventList]; } - (id)copyWithZone:(NSZone *)zone { MOEventData *copy = [[MOEventData alloc] init]; if (copy) { copy.eventList = [self.eventList copyWithZone:zone]; } return copy; } @end