我有一个运行简单计时器的应用程序。以下代码每秒从 NSTimer 运行几次。作为一名新的 iOS 开发人员,我将第一个承认内存管理是我目前最薄弱的技能。当我运行这段代码时,如果我让计时器运行一段时间,我就会开始收到内存警告,并最终崩溃。如果我禁用 NSTimer,它可以正常运行数小时。我看不出是什么导致了泄漏:
- (void)onTimerTick
{
NSDate *date = [NSDate date];
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger hour = [dateComponents hour];
NSInteger min = [dateComponents minute];
NSInteger sec = [dateComponents second];
double milliSince1970 = [date timeIntervalSince1970];
int secsSince1970 = [date timeIntervalSince1970];
int frame = (((milliSince1970 - secsSince1970) * 1000) / frameDuration) + 1;
timeCode.text = [NSString stringWithFormat:@"%d:%d:%d:%d", hour, min, sec, frame];
[calendar dealloc];
}
如有任何帮助,我们将不胜感激!
最佳答案
调用[calendar release]
,而不是dealloc
...框架在calendar
时调用dealloc
不再有任何东西保留它。
关于iphone - 在这段短代码中找不到内存泄漏的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5863017/