7

Tengo una clase personalizada que deseo guardar y cargar. La clase contiene un NSDate, un NSString y un NSNumber. Implementé el protocolo NSCoding en el archivo .h. Aquí está el código que tengo hasta ahora. theDate es un NSDate. theName es el NSString. homeAway es el NSNumber.Cómo codificar y decodificar una clase personalizada con NSKeyedArchiver

-(void)encodeWithCoder:(NSCoder *)aCoder { 
[aCoder encodeObject:theDate forKey:@"theDate"]; 
[aCoder encodeObject:theName forKey:@"theName"]; 
[aCoder encodeObject:homeAway forKey:@"homeAway"]; 
} 

-(id)initWithCoder:(NSCoder *)aDecoder { 
if ((self = [super init])) { 
    theDate = [aDecoder decodeObjectForKey:@"theDate"]; 
    theName = [aDecoder decodeObjectForKey:@"theName"]; 
    homeAway = [aDecoder decodeObjectForKey:@"homeAway"]; 
} 
return self; 
} 

Estoy utilizando el siguiente código para cargar mi objeto personalizado. Cuando uso print-object en el Depurador solo el homeAway aparece como un objeto real. theDate y theName dicen que 0x4e4f150 no parece apuntar a un objeto válido.

[gamesArray setArray:[NSKeyedUnarchiver unarchiveObjectWithFile:path]]; 
Game *loadedGame = [gamesArray objectAtIndex:gameNumber]; 

que guardar los datos utilizando el siguiente código:

Lo utilizo para llamar a mi clase para crear un nuevo juego (la clase personalizada que estoy tratando de guardar). El código hasta NSDate * aDate = [gameDate date]; es irrelevante.

-(void)newGame { 
if (homeAway != 0) { 
    if (dateChanged == 1) { 
     if ([nameField.text length] > 0) { 
      [homeButton setImage:[UIImage imageNamed:@"HomeGray.png"] forState:UIControlStateNormal]; 
      [awayButton setImage:[UIImage imageNamed:@"AwayGray.png"] forState:UIControlStateNormal]; 
      [dateButton setImage:[UIImage imageNamed:@"DateGray.png"] forState:UIControlStateNormal]; 
      [nameField setBackground:[UIImage imageNamed:@"textField.png"]]; 
      NSDate *aDate = [gameDate date]; 
      NSString *aString = [[[NSString alloc] initWithString:[nameField text]] autorelease]; 
      UIApplication *app = [UIApplication sharedApplication]; 
      [[[(miShotTrackAppDelegate *)[app delegate] viewController] courtViewOne] newGame:aDate withName:aString andPlace:homeAway]; 
      [loadTable reloadData]; 
      datePicke = 0; 
      homeAway = 0; 
      dateChanged = 0; 
      nameField.text = @""; 
      [self goBack]; 
      [self autoSave]; 
     } 
    } 
} 

}

A partir de ese método que llamo el método newGame cuales es

-(void)newGame:(NSDate *)theDate withName:(NSString *)theName andPlace:(int)homeAway { 

Game *newGame = [[Game alloc] init]; 
NSDate *tDate = [NSDate new]; 
tDate = theDate; 
[newGame setTheDate:tDate]; 
NSString *tString = [NSString stringWithString:theName]; 
[newGame setTheName:tString]; 
NSNumber *theNumber = [NSNumber numberWithInt:homeAway]; 
[newGame setHomeAway:theNumber]; 
[gamesArray addObject:newGame]; 
gameNumber = [gamesArray count] - 1; 
NSString *path = [self findGamesPath]; 
[NSKeyedArchiver archiveRootObject:gamesArray toFile:path]; 
[newGame release]; 
} 

¿Por qué mis objetos no ahorrar? ¿Copiar mis objetos tiene algo que ver con eso? Obtengo un error en la línea comentada que dice "exc bad access". Por favor, ayuda ...

Respuesta

6

No estás implementando -initWithCoder correctamente. -decodeObjectForKey devuelve un objeto liberado automáticamente. Entonces, por la forma en que escribiste el método, terminas con punteros colgantes para todos tus ivars de juego. Cambiar -iniciar ConCoder a:

-(id)initWithCoder:(NSCoder *)aDecoder 
{ 
    if ((self = [super init])) { 
    [self setTheDate:[aDecoder decodeObjectForKey:@"theDate"]]; 
    [self setTheName:[aDecoder decodeObjectForKey:@"theName"]]; 
    [self setHomeAway:[aDecoder decodeObjectForKey:@"homeAway"]]; 
    } 
    return self; 
} 

y debería funcionar para usted.

+0

Gracias ... ¡funcionó! –

+0

¡Gracias por esto! Debo añadir a esta publicación: ¡no olvide llamar a las funciones de ** super ** también! Si no haces esto, terminarás con resultados extraños. Entonces: 'if ((self = [super initWithCoder: aDecoder])) {' en el ejemplo anterior. – Ramon

Cuestiones relacionadas