简体   繁体   English

保留/释放-参考计数

[英]Retain / Release - Reference Count

Please kindly point out what is wrong in my code. 请指出我的代码有什么问题。 I define a variable idleTimer of my custom type 我定义了自定义类型的变量idleTimer

@property (nonatomic, retain) IdleTimer *idleTimer; @属性(非原子,保留)IdleTimer * idleTimer;

Then when I run the following codes, it crashes. 然后,当我运行以下代码时,它崩溃了。

IdleTimer   *idleTimerTemp  =   [[IdleTimer alloc] initTimer:PERIOD_COUPON_POPUP];
idleTimer   = idleTimerTemp;

NSLog(@"Pt. 1 %d %d", [idleTimerTemp retainCount], [idleTimer retainCount]);

[idleTimer setDelegate:self];
[idleTimerTemp release];
NSLog(@"Pt. 2 %d %d", [idleTimerTemp retainCount], [idleTimer retainCount]);

If the idleTimer is used again, it crashes. 如果再次使用idleTimer,它将崩溃。

But it I retain the idleTimerTemp on "idleTimer = idleTimerTemp". 但是我将idleTimer = idleTimerTemp上的idleTimerTemp保留了下来。 No crash at all. 完全没有崩溃。

But my variable is defined as retain. 但是我的变量定义为保留。 what is wrong ? 怎么了 ?

You're assigning to the idleTimer ivar directly instead of using the accessors. 您将直接分配给idleTimer ivar,而不是使用访问器。 Do this instead: 改为这样做:

self.idleTimer = idleTimerTemp;

The property accessors can't implement the semantics you specify if you don't use them. 如果不使用属性访问器,则无法实现您指定的语义。

Your property is defined as retain but that doesn't do anything with respect to the instance variable which is the backing storage for the property. 您的属性被定义为retain但是对于实例变量(该属性的后备存储)没有任何作用。 Presumably somewhere in your code, you've done an @synthesize idleTimer; 大概在代码中的某个地方,您已经完成了@synthesize idleTimer; . That creates an accessor pair which implements the memory management you requested. 这将创建一个访问器对,以实现您请求的内存管理。

The only way to get that behavior is to call the accessor itself. 获得该行为的唯一方法是调用访问器本身。 So if you assign directly to idleTimer , that does nothing, but if you use self.idleTimer = idleTimerTemp , then the -setIdleTimer: accessor gets called, which will retain the parameter. 因此,如果您直接分配给idleTimer ,则不会执行任何操作,但是如果您使用self.idleTimer = idleTimerTemp ,则会调用-setIdleTimer:访问器,它将保留该参数。

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

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