W swojej metodzie opisu nie korzystasz z właściwości, uzyskujesz dostęp do ivar.
-(NSString*) description
{
return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >",
timestamp,
startTime]; // <-- This is accessing the instance variable, not the property.
}
To będzie pracować dla Ciebie:
-(NSString*) description
{
return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >",
timestamp,
self.startTime]; // <-- This is using the property accessor.
}
Rzecz nieruchomość-vs-ivar bałagan ludzi cały czas, więc wybacz mi, a ja wędrówka na ten temat na minutę. :) Jeśli już to wszystko wiesz, przejdź dalej.
Po utworzeniu i syntezy nieruchomości, jak to było wyżej, dwie rzeczy:
- Ivar jest tworzona od właściwego typu.
- Funkcja getter jest tworzona, która zwraca tę wartość.
Ważną częścią o punkcie 2 jest to, że domyślnie na ivar oraz funkcję pochłaniacza (a zatem właściwość) mają takie same nazwy.
Więc tak:
@interface Event
@property(nonatomic, assign) NSUInteger timestamp;
@property(nonatomic, readonly, getter = timestamp) NSUInteger startTime;
@end
@implementation Event
@synthesize timestamp, startTime;
@end
...zamienia się w ten sposób:
@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
Jak kropka składnia działa to, że w ten sposób:
NSUInteger foo = myEvent.startTime;
naprawdę
NSUInteger foo = [myEvent startTime];
Wszystko to znaczy, że podczas dostępu do ivar, jesteś ... cóż, dostęp do ivar. Gdy używasz właściwości, wywołujesz funkcję, która zwraca wartość. Co ważniejsze, bardzo łatwo jest zrobić jedno, gdy chodzi o drugie, ponieważ składnia jest bardzo podobna. Z tego powodu wiele osób rutynowo syntetyzuje swoje ivars z wiodącymi znakami podkreślenia, tak że trudniej jest zepsuć.
@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. :)
Jaki jest błąd? Z 'getter'? –
Właściwie moja odpowiedź była błędna. Nie ma znaczenia, czy masz wiele właściwości powiązanych z tym samym selektorem. Powiedziałbym, że nie ma z tym problemu ... –
@ RichardJ.RossIII Przeprowadziłem test tylko w najnowszym XCode w projekcie ARC. Być może była to zmiana w Clangu w pewnym momencie. – Joe