years.text = [NSString stringWithFormat:@"%0.1f", theScroller.contentOffset.y];
将避免需要显式释放字符串,因为它是自动释放的。
但是,如果您试图避免放缓,请考虑更新频率更低。例如,每次调用scrollViewDidScroll
时,都要设置一个定时器,以便从现在开始在0.1秒内更新字段,但如果定时器已经从先前的调用中运行,则不会。这可以在保持UI更新的同时减少通话次数。
下面是一个如何做到这一点的例子。在滚动视图代表的接口声明中声明的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
的时间间隔,你可以尝试使它更快或更慢,看看什么效果最好。
请注意,就内存管理而言,此示例是完整的。您不应该尝试保留或释放计时器对象。它的生命周期由runloop在内部处理。
这只是一个方便的方法,在后台分配字符串。这不是一个替代方案。 – Chuck 2011-03-16 09:04:32
我现在添加了一个更完整的答案。 – 2011-03-16 09:08:52
非常感谢,我要设置一个计时器.. – mtompson 2011-03-16 09:19:35