Nstimer retain its target.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.