objective-c - NSString 分配与否!

标签 objective-c nsstring alloc

我正在从 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/

相关文章:

iphone - XCode:单个 ViewController 转到多个 ViewController

objective-c - 直接初始化的委托(delegate)生成 ARC 警告和 EXC_BAD_ACCESS 崩溃

iphone - 检查 NSDictionary 中的键是否为空

c - 释放结构数组

ios - 我们如何在 xCode iOS 中隐藏敏感数据

ios - 使用 UIRefreshControl 在 TableView 中置换标题

ios - iOS-获取高度NSString

objective-c - stringWithContentsOfFile :encoding:error: error 260

iphone - 为什么不建议用id分配和初始化?