我是一名初出茅庐的 iPhone 开发人员,所以请对我放轻松。
我正在尝试开发一个简单 应用程序,它将显示时间然后每秒滴答作响。我觉得我在内存管理方面遗漏了一些东西,但我的技能太新了,无法真正知道我遗漏了什么。
我正在创建一个直接指向主窗口的标签(非常简单的应用程序)并尝试通过 NSTimer
更新标签。这是我的一些代码,它仍然有点困惑。
@synthesize label, theDate;
@synthesize window;
- (void)tick
{
theDate = [[NSDateFormatter alloc] init];
[theDate setDateFormat:@"hh:mm:ss"];
NSString* currentTime = [theDate stringFromDate:[NSDate date]];
label.text = [[NSString alloc] initWithFormat:@"%d",currentTime];
[currentTime release];
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CGRect rect = CGRectMake(10, 200, 300, 20);
label = [[UILabel alloc] initWithFrame:rect];
label.textAlignment = UITextAlignmentCenter;
[self.window addSubview:label];
[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(tick)
userInfo:nil
repeats:YES];
[self.window makeKeyAndVisible];
return YES;
}
@synthesize
的ivars是.h文件中的@property
,并且ivars在dealloc中被释放。
谢谢!
最佳答案
这里有很多内存问题:
- 您正在分配
theDate
但没有释放它,所以它正在泄漏。 - 尽管没有拥有引用,但您正在释放
currentTime
,因此您可能会在自动释放池中看到崩溃。 - 您正在分配分配给
label.text
的值但没有释放它; label.text 是一个保留属性,在这种情况下,您通过双重保留它来泄漏该字符串,或者 label.text 不保留,在这种情况下,您通过从不释放它来泄漏字符串(最后一个除外) , 在 dealloc 中)
我强烈建议您阅读 Apple's memory management guide .
此外,与内存问题无关,您正在使用 %d
来尝试显示字符串而不是 %@
,因此您将获得数值指针地址而不是字符串的内容。
关于iphone - 如何在标签中增加 NSTimer 的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5004983/