Thursday, March 31, 2011

Using a timed NSInvocation to animate the population of a UITableView

While there's probably dozens of ways to animate the population of a UITableView, here's one way using NSInvocation with a timer. I hadn't used NSInvocation before so this was a good exercise.

The example:
1. Configures the cell
2. Sets the cell's "hidden" attribute to true
3. Creates an NSInvocation for the "setHidden" attribute of the cell
4. Configures the NSInvocation argument to set setHidden to "NO"
5. Creates a timer that fires the NSInvocation at a relative time

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        (*** set the cell data here)

        [cell setHidden:YES];
        NSMethodSignature * mySignature = [UITableViewCell instanceMethodSignatureForSelector:@selector(setHidden:)];
        NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature:mySignature];
        NSNumber *n = [NSNumber numberWithBool:NO];
        [myInvocation setArgument:&n atIndex:2];
        [myInvocation setTarget:cell];
        [myInvocation setSelector:@selector(setHidden:)];
        [NSTimer scheduledTimerWithTimeInterval:.1 * indexPath.row invocation:myInvocation repeats:NO];
        return cell;

1 comment:

  1. This is wrong. setHidden: does not take an NSNumber object. it takes a BOOL