3

我从 scrollViewDidScroll 方法运行这段代码(所以它在你滚动时运行!):

NSString *yearCount = [[NSString alloc] initWithFormat:@"%0.1f", theScroller.contentOffset.y];  
years.text = yearCount; 
[yearCount release];

效果很好,但是它会影响滚动的性能(导致它在减速时颤抖)

我的问题是,我是否需要继续使用 alloc 和 release 或者有没有办法在没有它的情况下使用 initWithFormat 获取一些数字?

4

3 回答 3

3
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用作时间间隔,您可以尝试使其更快或更慢,看看哪种效果最好。

请注意,就内存管理而言,此示例是完整的,您不应尝试自己保留或释放计时器对象。它的生命周期由运行循环在内部处理。

于 2011-03-16T08:58:45.870 回答
2

考虑使用scrollViewDidEndDecelerating避免频繁更新的方法。alloc-init 不对性能下降负责,频繁设置文本是。除非您真的需要连续更改它(在这种情况下,可以选择使用计时器的解决方案),否则您应该寻找不同的钩子方法。

于 2011-03-16T09:08:20.563 回答
1

您的性能很差,绝对不是因为字符串格式或分配释放。您可以使用一些较短的形式,例如:

years.text = [NSString stringWithFormat:@"%0.1f", theScroller.contentOffset.y];

这相当于

years.text = [[[NSString alloc] initWithFormat:@"%0.1f", theScroller.contentOffset.y] autorelease];

但是,这根本无助于提高您的表现。

于 2011-03-16T09:01:49.850 回答