steveY
steveY

Reputation:

iphone indexed table view problem

I have a table view in which I'm using sectionIndexTitlesForTableView to display an index. However, when I scroll the table, the index scrolls with it. This also results in very slow refreshing of the table. Is there something obvious I could be doing wrong? I want the index to remain in place on the right while the table scrolls. This is the code I'm using for the index titles:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    [tempArray addObject:@"A"];
    [tempArray addObject:@"B"];
    [tempArray addObject:@"C"];
    [tempArray addObject:@"D"];
...

    return tempArray; 
}

Upvotes: 0

Views: 6245

Answers (3)

iUrii
iUrii

Reputation: 13818

Make a static variable, it will be released on app exit.

static NSMutableArray* alphabet = nil;

+ (void)initialize {
    if(self == [MyViewController class]){
        NSUInteger const length = 'Z' - 'A' + 1;
        alphabet = [[NSMutableArray alloc] initWithCapacity:length];
        for(NSUInteger i=0; i<length; ++i){
            unichar chr = 'A' + i;
            [alphabet addObject:[NSString stringWithCharacters:&chr length:1]];
        }
    }
}

Upvotes: 1

Ramin
Ramin

Reputation: 13433

You really should be creating the index list somewhere else (say, in your table controller's init or loadView methods) and retaining it as an instance variable for later use. Then in sectionIndexTitlesForTableView you only have to return that ivar. If it isn't a property with a retain attribute then make sure you retain it when created so it sticks around (and release it in dealloc).

An easy way to create it is:

self.alphabetIndex = [NSArray arrayWithArray:
   [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
         componentsSeparatedByString:@"|"]];

The actual letters would have to change depending on the language locale setting but this way it's a bit easier to localize.

You definitely don't want to be creating that temp array each time because it's going to get called a lot.

As far as the index scrolling away it may be related to your returning a new array each time. Try the above first and if it doesn't solve the problem then you may want to tweak the value for the table's sectionIndexMinimumDisplayRowCount property and see if it makes any difference.

Upvotes: 3

slf
slf

Reputation: 22777

I would avoid creating a new NSMutableArray and releasing it every time. Try creating those on viewDidLoad or the class constructor and just reference the pre-built array on sectionIndexTitesForTableView.

If you are not manipulating the array at all, you probably don't need the overhead of an NSMutableArray at all. Try switching it to a plain old NSArray by using the arrayWithObjects static autorelease constructor.

That should speed things up for you.

Upvotes: 1

Related Questions