Nel metodo della descrizione, non si sta utilizzando la proprietà, si sta accedendo a ivar.
-(NSString*) description
{
return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >",
timestamp,
startTime]; // <-- This is accessing the instance variable, not the property.
}
Questo funziona per voi:
-(NSString*) description
{
return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >",
timestamp,
self.startTime]; // <-- This is using the property accessor.
}
La cosa proprietà-vs-Ivar scombina la gente per tutto il tempo, così mi scusi, mentre io divagare a questo proposito per un minuto. :) Se già conosci tutto questo, salta.
Quando si crea e sintetizzare una proprietà, come avete fatto in precedenza, accadono due cose:
- un Ivar è creato del tipo corretto.
- viene creata una funzione getter, che restituisce tale ivar.
La parte importante attorno al punto 2 è che, per default, l'ivar e la funzione getter (e quindi, la proprietà) hanno gli stessi nomi.
Quindi questo:
@interface Event
@property(nonatomic, assign) NSUInteger timestamp;
@property(nonatomic, readonly, getter = timestamp) NSUInteger startTime;
@end
@implementation Event
@synthesize timestamp, startTime;
@end
...si trasforma in questo:
@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
Come funziona la sintassi del punto è che questo:
NSUInteger foo = myEvent.startTime;
fa davvero
NSUInteger foo = [myEvent startTime];
Tutto questo per dire che quando si accede a un Ivar, sei ... beh, accedendo a un ivar. Quando si utilizza una proprietà, si chiama una funzione che restituisce un valore. Ancora più importante, è estremamente facile fare una cosa quando si intende l'altra, perché la sintassi è molto simile. È per questo motivo che molte persone sintetizzano abitualmente i loro ivar con i caratteri di sottolineatura principali, quindi è più difficile incasinare.
@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. :)
Qual è l'errore? Con 'getter'? –
In realtà, la mia risposta era sbagliata. Non importa se hai più proprietà collegate allo stesso selettore. Direi che non c'è alcun problema con questo ... –
@ RichardJ.RossIII Ho eseguito il mio test solo nell'ultimo XCode in un progetto ARC. Potrebbe essere possibile che questo fosse un cambiamento in Clang ad un certo punto. – Joe