我正在从 scrollViewDidScroll 方法运行这段代码(所以它会在您滚动时运行!):
NSString *yearCount = [[NSString alloc] initWithFormat:@"%0.1f", theScroller.contentOffset.y];
years.text = yearCount;
[yearCount release];
它工作正常,但是它影响了滚动的性能(导致它在减速时抖动)
我的问题是,我是否需要继续使用 alloc 和 release,或者有没有办法在没有它的情况下使用 initWithFormat 获取一些数字到一些文本上?
最佳答案
years.text = [NSString stringWithFormat:@"%0.1f", theScroller.contentOffset.y];
将避免显式释放字符串的需要,因为它是自动释放的。
但是,如果您试图避免速度变慢,请考虑降低更新字段的频率。例如,每次调用 scrollViewDidScroll
时,设置一个计时器以在从现在起 0.1 秒后更新字段,但如果计时器已经从上一次调用开始运行,则不会。这减少了调用次数,同时保持 UI 更新。
这是一个如何做到这一点的例子。在 ScrollView 委托(delegate)的接口(interface)声明中声明一个 NSTimer
:
NSTimer *timer;
和方法:
- (void)updateYear:(NSTimer*)theTimer
{
timer=nil;
UIScrollView *theScroller=[theTimer userInfo];
years.text=[NSString stringWithFormat:@"%0.1f", theScroller.contentOffset.y];
}
- (void)scrollViewDidScroll:(UIScrollView *)theScroller
{
if (!timer) {
timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateYear:) userInfo:theScroller repeats:NO];
}
}
显然,您不必使用 0.1
作为时间间隔,您可以尝试使其变快或变慢,看看哪种效果最好。
请注意,就内存管理而言,此示例是完整的,您不应尝试自己保留或释放计时器对象。它的生命周期由运行循环在内部处理。
关于objective-c - NSString 分配与否!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5322744/