2
4

1 回答 1

1

You're probably getting input that has no hyphen, so the location of the the hyphen is NSNotFound which is defined to be NSIntegerMax, I believe. Your code needs to be robust to this.

This is a bit different from how you're doing it now, but it should work on more types of input:

NSString *infoString = @"ARTIST - TRACK";
NSArray *infoStringComponents = [infoString componentsSeparatedByString:@" - "];
__block NSString *artistString = @"";
__block NSString *trackInfoString = @"";

if ([infoStringComponents count] == 0) {
    // This case should only happen when there's no info string at all
    artistString = @"Unknown Artist";
    trackInfoString = @"Unknown Song";
}
else if ([infoStringComponents count] == 1) {
    // If no hyphens just display the whole string as the track info
    trackInfoString = infoStringComponents[0];
}
else {
    [infoStringComponents enumerateObjectsUsingBlock:^(NSString *component, NSUInteger index, BOOL *stop) {
        NSString *trimmedComponent = [component stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (index == 0) {
            artistString = trimmedComponent;
        }
        else {
            NSString *buffer = @"";
            if ([trackInfoString length] > 0) {
                buffer = @" - ";
            }
            trackInfoString = [trackInfoString stringByAppendingFormat:@"%@%@",buffer,trimmedComponent];
        }
    }];
}

You could also check if the location property of the range you derive is equal to NSNotFound and then just assume you can't derive an artist out of it and display your _metaData variable in an appropriate label. For example:

NSRange hyphenRange = [infoString rangeOfString:@"-"];
if (hyphenRange.location == NSNotFound) {
    // Display only infoString to the user, unformatted into artist / song info
}
else {
    // Try the same technique you're attempting now
}
于 2013-11-07T04:04:44.133 回答