I need to parse and sort an array with 100+ entries. I have the method for parsing and sorting it below. The catch: I need it the strings stored in the NSMutableArray to be displayed in a tableView immediately when the ViewController that holds the tableView is presented/loaded. If I don’t do this, the UI hangs/freezes when invoking the ViewController. Moving the code into one of my singletons, increases boot time, which I also need to avoid.
I think I have to Queue/Block this code, but I’m not sure how to do it. Any guidance is greatly appreciated!
Here’s the code I have to parse [NSTimeZone knownTimeZones]:
-(void)parseTimeZoneNames {
for (int i = 0; i < [[NSTimeZone knownTimeZoneNames] count]; i++) {
NSString *fullName = [NSString stringWithFormat:@"%@", [[NSTimeZone knownTimeZoneNames] objectAtIndex:i]];
NSRange firstForwardSlash = [fullName rangeOfString:@"/"];
NSRange firstNameRange = NSMakeRange(firstForwardSlash.location + 1, ([fullName length] - firstForwardSlash.location - 1));
NSString *cityName = [NSString stringWithFormat:@"%@", [fullName substringWithRange:firstNameRange]];
NSRange secondforwardSlash = [cityName rangeOfString:@"/"];
if(!secondforwardSlash.length) {
NSRange secondNameRange = NSMakeRange(secondforwardSlash.location + 1, ([cityName length] - secondforwardSlash.location - 1));
cityName = [NSString stringWithFormat:@"%@", [cityName substringWithRange:secondNameRange]];
}
NSRange underscore = [cityName rangeOfString:@"_"];
if(!underscore.length) {
NSRange finalNameRange = NSMakeRange(underscore.location + 1, ([cityName length] - underscore.location - 1));
cityName = [NSString stringWithFormat:@"%@", [cityName substringWithRange:finalNameRange]];
}
[timeZonesArray addObject:cityName];
}
[timeZonesArray sortUsingSelector:@selector(compare:)];
}
Here’s the code for presenting it in the same ViewController:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[NSTimeZone knownTimeZoneNames] count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:@"%@", [timeZonesArray objectAtIndex:indexPath.row]];
return cell;
}
If the code really is too slow then you can pre-sort the data yourself and add it to a plist in your app bundle.
The time zones in the world aren’t going to change. If they do, we’ve got bigger things to worry about than your app missing a few out.