Objective-C property - getter behavior

What is technically wrong with the following:

@property(nonatomic, assign) NSUInteger timestamp;
@property(nonatomic, readonly, getter = timestamp) NSUInteger startTime;
@property(nonatomic, assign) NSUInteger endTime;

I'm sure I can find a better way to organize this, but this is what I came across at some point in my project, and I noticed that access to the startTime property always returned 0, even when the timestamp property was set to the correct label time .

It seems by setting getter startTime to an existing property (timestamp), it does not forward the timestamp value when I do this:

event.startTime => 0
event.timestamp => 1340920893

These are all timestamps, by the way.

Just a reminder, I know this happened in my project, but I don’t understand why access to startTime is not redirected to the timestamp property.

UPDATE

In my implementation, I synthesize all of these properties:

@synthesize timestamp, endTime, startTime;

, , GitHub: https://gist.github.com/3013951

+5
2

, ivar.

-(NSString*) description
{
    return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >", 
             timestamp, 
             startTime]; // <-- This is accessing the instance variable, not the property.
}

:

-(NSString*) description
{
    return [NSString stringWithFormat:@"Event< timestamp:%d, start:%d >", 
             timestamp, 
             self.startTime]; // <-- This is using the property accessor.
}

-vs-ivar , , .:) , .

, , :

  • .
  • getter, ivar.

2 , ivar getter (, , ) .

, :

@interface Event
@property(nonatomic, assign) NSUInteger timestamp;
@property(nonatomic, readonly, getter = timestamp) NSUInteger startTime;
@end

@implementation Event
@synthesize timestamp, startTime;
@end

... :

@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

:

NSUInteger foo = myEvent.startTime;

NSUInteger foo = [myEvent startTime];

, , , ivar, ... , ivar. , , . , , , . , .

@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.  :)
+5

, , startTime.

//implementation
@synthesize timestamp;
@synthesize statTime;
+1

All Articles