Salvando um NSArray de objetos personalizados
Eu criei uma subclasse de UIImage (UIImageExtra) como eu quero incluir propriedades e métodos extras.
Eu tenho uma matriz que contém instâncias desta classe personalizada.No entanto, quando eu salvar a matriz, parece que os dados extras na classe UIImageExtra não são salvos.
O UIImageExtra está em conformidade com o NSCoding, mas nem o initWithCoder nem o encodeWithCoder são chamados, pois as instruções do NSLog que adicionei não são impressas.
Meu método para salvar o array é assim:
<code>- (void)saveIllustrations { if (_illustrations == nil) { NSLog(@"Nil array"); return; } [self createDataPath]; //Serialize the data and write to disk NSString *illustrationsArrayPath = [_docPath stringByAppendingPathComponent:kIllustrationsFile]; NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:_illustrations forKey:kIllustrationDataKey]; [archiver finishEncoding]; [data writeToFile:illustrationsArrayPath atomically: YES]; } </code>
E o UIImageExtra possui os seguintes métodos de delegação para salvar:
<code> #pragma mark - NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder { NSLog(@"Encoding origin data!"); [super encodeWithCoder:aCoder]; [aCoder encodeObject:originData forKey:kOriginData]; } - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super initWithCoder:(NSCoder *) aDecoder]) { NSLog(@"Decoding origin data"); self.originData = [aDecoder decodeObjectForKey:kOriginData]; } return self; } </code>
Meu código para criar o array em primeiro lugar se parece com isso (no caso de oferecer alguma pista)
<code> for (NSDictionary *illustrationDict in illustrationDicts) { NSString *illustrationString = [illustrationDict objectForKey:@"Filename"]; NSNumber *xCoord = [illustrationDict objectForKey:@"xCoord"]; NSNumber *yCoord = [illustrationDict objectForKey:@"yCoord"]; UIImageExtra *illustration = (UIImageExtra *)[UIImage imageNamed:illustrationString]; //Scale the illustration to size it for different devices UIImageExtra *scaledIllustration = [illustration adjustForResolution]; NSValue *originData = [NSValue valueWithCGPoint:CGPointMake([xCoord intValue], [yCoord intValue])]; [scaledIllustration setOriginData:originData]; [self.illustrations addObject:scaledIllustration]; } </code>
Ou estou apenas salvando esses dados da maneira errada? Muito Obrigado.