0

I have an NSThread that runs the following code:

for (Experiment *exp in experiments) {
    ExperimentBlock *block = [[ExperimentBlock alloc] initWithFrame:CGRectMake(0, maxHeight, 310, 50)
                                                         experiment:exp
                                                             target:self
                                                             action:@selector(onExperimentButtonClicked:)];
    [scrollView addSubview:block];
    // block cannot be released for some inadequately explained reason
    maxHeight += 60;
}

Good memory management practice expects us to release any objects we have allocated, copied or new'ed. However, when my thread finishes, if I have released (or autoreleased) the blocks I've added to my UIScrollView, the objects are displayed in my UIScrollView for a second before disappearing.

How should I release the memory without losing these objects?

Mxyk
  • 10,678
  • 16
  • 57
  • 76
Jaypoulz
  • 110
  • 11

1 Answers1

4

You must never modify a view (call addSubview:) on a background thread. This is why you're getting strange behaviors. You must call addSubview: on the main thread.

This type of work is typically much better done with GCD or NSOperationQueue. Manual NSThread is less efficient in most cases and more difficult to code correctly. You can move your addSubview: calls to the main queue like this:

dispatch_async(dispatch_get_main_queue(), ^{
  [self.scrollView addSubview:block];
  [block release];
});

The call to self here is intentional. It creates a temporary retain loop that ensures we cannot be deallocated until this code runs.

Switching this project to ARC would simplify memory management here, and is recommended.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610