A class object B has been released today (there is a timer in this class), and according to the principle of arc, the retaincount of B is 0 o'clock and the dealloc is called. But when the b=nil for me, did not enter the Dealloc.
-(void) dealloc
{
[Timer invalidate];
Timer = nil;
}
Later, after a friend reminded that Nstimer to the Class B has a reference, that is, at the initialization of the target has retain.
Timer = [Nstimer scheduledtimerwithtimeinterval:1.0 self selector: @selector (logout:) Userinfo:nil Repeats:yes];
Later changed self to __weak, found also not.
__weak id weakself = self;
Timer = [Nstimer scheduledtimerwithtimeinterval:1.0 target:weakself selector: @selector (logout:) Userinfo:nil repeats: YES];
Finally, a method of using proxies was found in StackOverflow.
Http://stackoverflow.com/questions/16821736/weak-reference-to-nstimer-target-to-prevent-retain-cycle
Create a separate Weaktimertarget
@interface Weaktimertarget:nsobject
{
__weak ID target;
SEL selector;
}
-(ID) Initwithtarget: (ID) TG selector: (SEL) sel;
-(void) Timerdidfire: (Nstimer *) timer;
@end
@implementation Weaktimertarget
-(ID) Initwithtarget: (ID) TG selector: (SEL) SEL
{
self = [super init];
target = TG;
selector = sel;
return self;
}
-(void) Timerdidfire: (Nstimer *) timer
{
if (target)
{
[Target Performselector:selector Withobject:timer];
}
Else
{
[Timer invalidate];
}
}
@end
This is used in class B:
Weaktimertarget *weaktarget = [[Weaktimertarget alloc] initwithtarget:self selector: @selector (logout:)];
[Nstimer scheduledtimerwithtimeinterval:1.0 target:weaktarget selector: @selector (timerdidfire:) userinfo:nil Repeats:yes];
This will solve the problem of not releasing memory, but why use __weak self and __strong self effect is the same do not know why, I hope you can advise.
Nstimer retain its target.