fuzzygoat
fuzzygoat

Reputation: 26223

Retaining object created by a class method?

This is probably something I should know by now, I am creating an instance of NSTimer using the NSTimer class method. I am pretty sure the returned object is autoreleased, my question is in terms of memory management should I be then retaining and releasing the timer object (METHOD: 1), or simply just assigning it directly to the @property (METHOD: 2)(or should I be doing something totally different?)

// METHOD: 1
@property (nonatomic, retain) NSTimer *myTimer;

.

NSTimer *tempTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(executeOnTimer) userInfo:nil repeats:YES];
    [self setMyTimer:tempTimer];
    //[tempTimer release];

.

- (void)dealloc {
    [pulseTimer release];
    [super dealloc];
}

OR SIMPLY:

// METHOD: 2
myTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(executeOnTimer) userInfo:nil repeats:YES];

EDIT:

One final point, if I just write (see below) without assigning to a property is there any chance that the timer is going to get deallocated, basically does it stay around until the program exits. Just curious how its retained?

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

Upvotes: 1

Views: 324

Answers (2)

Martin Babacaev
Martin Babacaev

Reputation: 6280

In order to take ownership over the NSTimer you can do one of these with the same effect:

self.myTimer = [NSTimer scheduledTimerWithTimeInterval: ...]; // implicit setter

or

[self setMyTimer: [NSTimer scheduledTimerWithTimeInterval:...]]; // explicit setter

or

myTimer = [[NSTimer scheduledTimerWithTimeInterval: ...] retain];

or

self->myTimer = [[NSTimer scheduledTimerWithTimeInterval: ...] retain];

Upvotes: 2

user142019
user142019

Reputation:

This is the good way:

self.myTimer = tempTimer;
// don't call [tempTimer release]

This will retain it automcailcally due to the property which retains it.

Just calling myTimer = … doesn't use the setter while self.myTimer = … does.

Upvotes: 1

Related Questions