En su método de descripción, no está utilizando la propiedad, está accediendo al ivar.
-(NSString*) description
{
return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >",
timestamp,
startTime]; // <-- This is accessing the instance variable, not the property.
}
Esto funcionará para usted:
-(NSString*) description
{
return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >",
timestamp,
self.startTime]; // <-- This is using the property accessor.
}
Lo propiedad-vs-Ivar se mete a la gente todo el tiempo, así que discúlpame mientras yo divagar sobre ello durante un minuto. :) Si ya sabes todo esto, salta hacia adelante.
Al crear y sintetizar una propiedad, como lo hizo anteriormente, suceden dos cosas:
- una Ivar se crea del tipo adecuado.
- se crea una función getter, que devuelve ese ivar.
La parte importante con respecto al punto 2 es que, por defecto, la Ivar y la función getter (y, por lo tanto, la propiedad) tienen los mismos nombres.
Así que esto:
@interface Event
@property(nonatomic, assign) NSUInteger timestamp;
@property(nonatomic, readonly, getter = timestamp) NSUInteger startTime;
@end
@implementation Event
@synthesize timestamp, startTime;
@end
...se convierte en esto:
@interface Event {
NSUInteger timestamp;
NSUInteger startTime;
}
@end
@implementation Event
- (NSUInteger) timestamp {
return timestamp
}
- (void) setTimestamp:(NSUInteger) ts {
timestamp = ts;
}
- (NSUInteger) startTime {
return [self timestamp];
}
@end
¿Cómo funciona la sintaxis de punto es que esto:
NSUInteger foo = myEvent.startTime;
realmente
NSUInteger foo = [myEvent startTime];
Todo eso quiere decir que cuando se accede a una Ivar, eres ... bueno, accediendo a un ivar. Cuando usa una propiedad, llama a una función que devuelve un valor. Más importante aún, es extremadamente fácil hacer una cosa cuando se refería a la otra, porque la sintaxis es muy similar. Es por esta razón que muchas personas sintetizan rutinariamente sus ivars con guiones bajos destacados, por lo que es más difícil equivocarse.
@property(nonatomic, assign) NSUInteger timestamp;
@property(nonatomic, readonly, getter = timestamp) NSUInteger startTime;
@synthesize timestamp = _timestamp;
@synthesize startTime = _startTime;
NSLog(@"startTime = %d", _startTime); // OK, accessing the ivar.
NSLog(@"startTime = %d", self.startTime); // OK, using the property.
NSLog(@"startTime = %d", startTime); // NO, that'll cause a compile error, and
// you'll say "whoops", and then change it
// to one of the above, thereby avoiding
// potentially hours of head-scratching. :)
¿Cuál es el error? Con 'getter'? –
En realidad, mi respuesta fue incorrecta. No importa si tiene múltiples propiedades vinculadas al mismo selector. Diría que no hay problema con esto ... –
@ RichardJ.RossIII Solo realicé mi prueba en el último XCode en un proyecto de ARC. Es posible que esto haya sido un cambio en Clang en algún momento. – Joe