2013-06-19 3 views
0

Я хотел бы сделать это как-то короче или меньше места.Создание метода внутри массива? или короче?

totalTime = [self timeFormatted:([currentFeed duration].intValue)-1]; 
    NSString *word = @":00:"; 
    if ([totalTime rangeOfString:word].location == NSNotFound) { 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"00:" withString:@""]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"01:" withString:@"1:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"02:" withString:@"2:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"03:" withString:@"3:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"04:" withString:@"4:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"05:" withString:@"5:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"06:" withString:@"6:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"07:" withString:@"7:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"08:" withString:@"8:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"09:" withString:@"9:"]; 
    } 

всякая помощь очень ценится.

ответ

2

Вы можете сделать totalTime в mutableString. Затем вы можете поместить свое сопоставление в NSDictionary и повторить его.

NSMutableString *ms = [[totalTime mutableCopy] autorelease]; 

NSDictionary *d = @{@"00":@"", @"01:":@"1:", @"02:":@"2:" /* ... */}; 

[d enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 
    [ms replaceOccurrencesOfString:key withString:obj options:NSCaseInsensitiveSearch range:NSMakeRange(0, [ms length])]; 
}]; 

totalTime = ms; 

Кстати, если вы пытаетесь отформатировать дату, посмотреть на NSDateFormatter reference.

+0

NSDictionary * d = {@ "00": @ "", @ "01:": @ "1:", @ "02:": @ "2:"}; Я пробовал это, и я получаю эту ошибку «Ожидаемый»} »« – IamGretar

+0

Ваш компилятор, вероятно, не использует литералы Objective-C. Попробуйте объявить словарь следующим образом: 'NSDictionary * d = [Словарь NSDictionaryWithObjectsAndKeys: @" ", @" 00 ", @" 1: ", @" 01: ", @" 2: ", @" 02 : ",/* ... */nil];' – nst

+0

вам не хватает @ перед изогнутыми скобками: 'NSDictionary * d = @ {@" 00 ": @" ", @" 01: ": @ "1:", @ "02:": @ "2:"}; ' – Herm

0

добавить категорию для NSString:

@implementation NSString (replace) 

-(void) replace:(NSString*)old with:(NSString*)new{ 

self = [self stringByReplacingOccurrencesOfString:old withString:new]; 
} 

поэтому вы должны вызывать только: [totalTime replace:@"00:" with:@""];

1

Принимая другой подход с регулярными выражениями:

NSError *error = NULL; 
// replace 0X: with X: where X is 1-9 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"0([1-9]:)" options:0 error:&error]; 
date = [regex stringByReplacingMatchesInString:date options:0 range:NSMakeRange(0,date.length) withTemplate:@"$1"]; 

// remove 00: if not preceded by : 
regex = [NSRegularExpression regularExpressionWithPattern:@"(?<!:)00:" options:0 error:&error]; 
date = [regex stringByReplacingMatchesInString:date options:0 range:NSMakeRange(0,date.length) withTemplate:@""]; 
Смежные вопросы