Objective c NSTimer内存管理问题

Objective c NSTimer内存管理问题,objective-c,memory-management,nstimer,nsthread,Objective C,Memory Management,Nstimer,Nsthread,默认情况下,通过方法alloc或copy返回的对象的retain count等于1,因此您必须自己释放它 但是通过NSTimer示例代码 // in one method start the timer (which myTimer is an Class Instance) myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(method:)

默认情况下,通过方法
alloc
copy
返回的对象的
retain count
等于1,因此您必须自己释放它

但是通过NSTimer示例代码

// in one method start the timer (which myTimer is an Class Instance) myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(method:) userInfo:nil repeats:YES]; // in another method [myTimer invalidate]; myTimer = nil; //在一个方法中,启动计时器(myTimer是类实例) myTimer=[NSTimer scheduledTimerWithTimeInterval:1 目标:自选择器:@selector(方法:) userInfo:nil repeats:YES]; //用另一种方法 [myTimer失效]; myTimer=nil;
我的问题是为什么[NSTimer sche**]返回一个您不需要保留的对象,但您可以在任何地方访问它。您无需释放它,只需在其上调用
invalidate

实例将保留在分配给它的运行循环中。 保留计数保持在零以上,直到运行循环将其释放。 因此,您可以访问对象,直到发生这种情况

从:

计时器与run一起工作 循环。要有效地使用计时器,您需要 应该知道如何运行循环 操作请参见nsrunlop和Threading 编程指南。特别注意 运行循环保留其计时器,因此 您可以在完成后释放计时器 将其添加到运行循环中

然后具体地说:

使用 scheduledTimerWithTimeInterval:调用:重复: 或 scheduledTimerWithTimeInterval:目标:选择器:用户信息:重复: 类方法来创建计时器和 在中的当前运行循环中计划它 默认模式

因此,您使用的方法会自动与当前运行循环一起工作