tags:

views:

24

answers:

1

If I wanted to create a simple class that has three instance variables and methods like

    NSInteger seconds;
    NSInteger minutes;
    NSTimer *timer;


- (void)setMinutes:(NSInteger)m;
- (void)setSeconds:(NSInteger)s;
- (NSInteger)minutes;
- (NSInteger)seconds;

What I want is to initialize a NSTimer object and have it countdown with those minutes/seconds. But I'm not sure how to initialize the timer, and release it if I need to (in the event I had multiple timers going). I know how to use the method:

[NSTimer scheduledTimerWithTimeInterval:1.0
                                target:self 
                               selector:@selector(doTimer:)
                               userInfo:nil
                                repeats:YES];

I don't see an example of NSTimer needing "alloc", or if it needs to be released as well.

A: 

scheduledTimerWithTimeInterval returns an instance of NSTimer. Just use properties and override the setter to invalidate the timer

    NSTimer *timer;

@property (nonatomic, retain) NSTimer *timer;
- (void)setTimer:(NSTimer *)t;



- (void)setTimer:(NSTimer *)t {
    if (timer) {
        [timer invalidate];
        [timer release];
        timer = nil;
    }

    timer = [t retain];
}

Her you have a pointer to the timer using self.timer, and when you set self.timer = newTimer, it retains the new one and invalidates and releases the old one.

Important to note is that your setter expects the input timer to be an autoreleased copy. If you plan on using the NSTimer scheduledTimerWithTimeInterval method you are already using, this will be fine.

coneybeare