简体   繁体   English

保留由类方法创建的对象?

[英]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. 这可能是我现在应该知道的事情,我正在使用NSTimer类方法创建NSTimer的实例。 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( METHOD:2 )(还是我应该做一些完全不同的事情?)

// 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];

In order to take ownership over the NSTimer you can do one of these with the same effect: 为了获得NSTimer的所有权,您可以执行以下操作之一,效果相同:

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

or 要么

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

or 要么

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

or 要么

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

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. 仅调用myTimer = …不会使用setter,而self.myTimer = …会使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM