NSString allocates or not!

I run this code from the scrollViewDidScroll method (so it runs when scrolling!):

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

which works great, however it affects performance on the scroll (making it shiver when it slows down)

My question is: do I need to continue to use alloc and release, or is there a way to get some numbers using initWithFormat, onto some text without it?

+3
source share
3 answers
years.text = [NSString stringWithFormat:@"%0.1f", theScroller.contentOffset.y];

avoids the need to explicitly free the string, as it is auto-implemented.

, , . , , scrollViewDidScroll, , 0,1 , . .


, . 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.

+3

scrollViewDidEndDecelerating, . Alloc-init , . ( ), hook.

+2

You have poor performance, not at all due to string formatting or release highlighting. You can use a shorter form, for example:

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

which is equivalent

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

However, this does not help improve performance.

+1
source

All Articles