NSDate scope question

  • Hi,

    I want to set a set a startDate when an object instance initializes
    and then periodically check it against the current date. I'm having
    difficulty getting it to work.

    NSDate *startDate;
    NSTimeInterval elapsedTime;
    NSTimer *timer;

    - init
    {
           [super init];

      startDate = [NSDate date];
               elapsedTime = 0;
      timer = [NSTimer scheduledTimerWithTimeInterval:1.0
        target:self selector:@selector(fireTimer:)
        userInfo:nil repeats:YES];

      return self;
    }

    - (void)fireTimer:(NSTimer *)timer
    {
      printf( "Count: %f\n", elapsedTime );
           elapsedTime = [startDate timeIntervalSinceNow];
    }

    This will compile, but fails at runtime and gives the error GDB:
    Program received signal: "EXC_BAD_ACCESS". when I step through in the
    debugger. It doesn't like any reference to startDate in the
    fireTimer: method, unless startDate is set within that method.

    I'm new to Cocoa and OOP in general, so I'm sure I'm probably just
    doing something stupid. Any suggestions would be greatly appreciated.

    Thanks,
    -Dan
  • On 4-Nov-06, at 8:33 AM, Dan Lemmon wrote:

    > This will compile, but fails at runtime and gives the error GDB:
    > Program received signal: "EXC_BAD_ACCESS". when I step through in
    > the debugger. It doesn't like any reference to startDate in the
    > fireTimer: method, unless startDate is set within that method.
    >
    > I'm new to Cocoa

    You aren't retaining 'startDate'
    You need to read about memory management in Cocoa.
    Start here: http://developer.apple.com/documentation/Cocoa/Conceptual/
    CocoaFundamentals/index.html
    and read the section "The Life Cycle of a Cocoa Object".

    --
    Cameron Hayne
    <hayne...>