UITableView insert rows crash

Discussion in 'iOS Programming' started by cruisercoder, May 11, 2009.

  1. cruisercoder macrumors newbie

    Joined:
    May 11, 2009
    #1
    I've simplified the code about as much as I can. It's a simple UITableView controller that inserts rows via a method in a separate thread at rate of 1 per second. The crash occurs when you scroll up after a page of rows have been added. The stack trace is deep within the UIKit run loop. There are no retains, but no releases here either and no instance variables managed, but I could be missing something.

    Code:
    #import "TableController.h"
    
    unsigned int size_ = 0;
    
    @implementation TableController
    
    -(id) init {
      if (self = [super init]) {
        self.title = @"View";
      }
      return self;
    }
    
    - (void)loadView  {
      UITableView *tableView = [[UITableView alloc] init];
    
      tableView.delegate = self;
      tableView.dataSource = self;
      tableView.rowHeight = 50;
      self.view = tableView; 
      [tableView reloadData];
      
      [NSThread detachNewThreadSelector:@selector(threadRun:) toTarget:self withObject:nil];
    }
    
    
    -(void) threadRun:(id) param {
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
      
      unsigned int pos = 0;
      do {
        
        pos = (++size_)-1;
        
        [self performSelectorOnMainThread:@selector(insertRow:)
          withObject:[[NSNumber numberWithInteger:pos] retain]
           waitUntilDone:YES];
        
        sleep(1);
        
      } while (pos != 20);
      
      [pool release]; 
    }
    
    
    - (void) insertRow:(NSNumber*) x {
      
      NSArray *insertIndexPaths = [NSArray arrayWithObjects:
          [NSIndexPath indexPathForRow:x.integerValue inSection:0],
          nil];
      
      UITableView *tv = (UITableView *) self.view; 
    
      [tv beginUpdates];
      [tv insertRowsAtIndexPaths:insertIndexPaths
          withRowAnimation:UITableViewRowAnimationTop];
      [tv endUpdates];
    }
    
    
    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
      UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"ident"];
    
      if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"ident"] autorelease];
      }
      
      cell.text = @"text";
      return cell;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
      return size_;
    }
    
    @end
    
     
  2. cruisercoder thread starter macrumors newbie

    Joined:
    May 11, 2009
    #2

Share This Page