I have a serious long else if statement which contains some links and some text. This is for Xcode 4, iOS 5 EDIT:
stationList = [[NSMutableArray alloc] init];
[stationList addObject:@"Q-dance Radio"];
[stationList addObject:@"The Voice"];
(ect ...)
[stationList sortUsingFunction:compareLetters context:nil];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([[stationList objectAtIndex:indexPath.row] isEqual:@"Q-dance Radio"])
{
[player pause];
NSString *u = @"LINK TO Q DANCE RADIO";
NSURL *url = [NSURL URLWithString:u];
player = [[AVPlayer alloc] initWithURL:url];
[player play];
}else if{
[player pause];
NSString *u = @"LINK TO THE VOICE";
NSURL *url = [NSURL URLWithString:u];
player = [[AVPlayer alloc] initWithURL:url];
[player play];
} (ect ...)
How can I make this better or make it find the pressed one faster, so it doesn't need to run though the whole list.
You could use an NSDictionary, and use the static strings as keys. I think you will get a good speedup from that. (The dictionary look-up probably hashes the input string that you use as a key.)
If you show more details, I can probably provide a more thorough answer. For example, you could even store the "do something here" code as a ^{} style block.
UPDATE I am at my computer now and can refer to some real code for you. This is based on something I have already done. YOur code may be modified this way:
xxxList = [[NSMutableArray alloc] init];
xxxListActionDictionary = [[NSMutableDictionary alloc] initWithCapacity:10]; // add this line
[xxxList addObject:@"TEXT HERE"];
[xxxListActionDictionary
setObject:
[[^{
// DO SOMETHING HERE. THIS IS A BLOCK. SOME CODE TO BE EXECUTED.
} copy] autorelease] // I don't think you need autorelease if you use ARC
forKey:@"TEXT HERE"]; // TEXT HERE is the same text put into the xxxListArray
ect.
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Here is where it gets efficient.
// The next three lines of code replace the entire if-else if...
void (^action)(void) = [xxxActionDictionary objectForKey:[[xxxList objectAtIndex:indexPath.row]];
if (action != nil) // you want to make sure the key is in the dictionary. may not be needed in your case.
action(); // this executes the block
UPDATE
stationList = [[NSMutableArray alloc] init];
[stationList addObject:@"Q-dance Radio"];
[stationListDictionary setObject:@"http://whateverQDanceRadioIs.com/folder/..." forKey:@"Q-dance Radio"];
[stationList addObject:@"The Voice"];
[stationListDictionary setObject:@"http://whateverTheVoiceIs.com/folder/..." forKey:@"Q-dance Radio"];
(ect ...)
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[player pause];
NSString *u = [stationListDictionary objectForKey[stationList objectAtIndex:indexPath.row]];
NSURL *url = [NSURL URLWithString:u];
player = [[AVPlayer alloc] initWithURL:url];
[player play];