ios 内存点滴

来源:互联网 发布:php免费源码下载 编辑:程序博客网 时间:2024/06/05 12:42

内存管理的理论知识我就不缀述了。(自行查阅,日常积累)

无论是c的手动释放内存 还是 objective-c里的arc方式,使用不当都会引起内存泄漏!


说说,最近在工程里看到的问题:


1. 犯了大错误  ”相互引用”   出了这种错误,哪种内存管理方式也帮不了,这是人祸!

比如 A.customDelegate=B ;  B.cusomDelegate=A;   (而且 @property(nonatomic, retain) id customDelegate)

这就是明显的相互引用。


2.关于NSTimer 的使用:

(1)

@property(nonatomic, retain) NSTimer *timer;

self.timer = [NSTimer scheduledTimerWithTimeInterval:0.04f target:self selector:@selector(check:) userInfo:nil repeats:YES];


释放:

- (void)dealloc{

...

if(self.timer){

[timer invalidate];

[timer release];

timer = nil;

}

}

这种方式理论上,没有问题,网上也好多帖子说,这么做。(例如:http://stackoverflow.com/questions/3439952/how-to-work-with-nstimer)


但我调度发现  timer每次调用时会对  self造成引用 计数加1   调用完成后,减1 (如果加1发生在  self 被释放同时就会造成 self释放不掉)


2)好的做法:

- (void)stopTimer{

if([timer isValid])

[timer invalidate]

释放前对象前,先停掉timer (理论支持: http://stackoverflow.com/questions/1876180/problem-invalidating-nstimer-in-dealloc)


原创粉丝点击