views:

764

answers:

2

I am trying to dynamically add subviews to a UiScorllView in real time (to save memory).

Doing so causes the scrollview to hang for a brief second... what is the way around this?

any hints appreciated

+2  A: 

Read up on the how the UITableView solves this problem. Your biggest performance hits here are the allocation and initial drawing of the subview, but primarily the allocation. UITableViews use a reuse identifier and an in-memory heap to keep all its cells in memory during scrolling so it can just reuse cells that have already been allocated instead of re-allocating new ones every time a new cell scrolls into the viewable area.

Perhaps you could implement your own subview reuse system to save yourself all that allocation time. Again, read up on specifically how the UITableView does it and model yours off of that. Unfortunately, there really is no easier solution than that that I can think of.

Marc W
+2  A: 

I suggest that any action that could possibly hang the user interface should be placed in a thread. This way, the process of adding the subview will be done in the background, not disturbing the main thread.

You could either do this by NSThread or you could implement the NSOperationQueue.

Declaration of the NSThread is simple;

[NSThread detachNewThreadSelector:@selector(myFunction:) toTarget:myObject withObject:argumentObject];

Where 'myFunction' should be replaced with the name of a function, the 'myObject' with an object (or simply state self if you want the current class to handle the thread) and 'argumentObject' should be replaced with any object you want to pass along as an argument; this may be nil

The function itself should look like this;

-(void)myFunction {
   NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
   // do your thing here...
   [pool release];
}

Every thread should have an autorelease pool.

One hint; if your subview has to animate, try declaring a UIAnimation block

MiRAGe