我想使用substringWithRange獲取NSString的子字符串:NSMakeRange。我從保存的字典中獲取初始字符串,保存的字符串被寫爲agent_AGENTNAME,我試圖剝離agent_部分。下面的代碼工作正常,如果(隨意批判它,如果它是原油)我硬編碼在爲NSMakeRange的數字 - 像這樣NSMakeRange崩潰應用程序
NSString* savedAgentName = [NSString stringWithFormat:@"%@", [thisfile substringWithRange:NSMakeRange(6,19)]];
但因爲每個人都將明顯具有不同長度的名字,我需要做這更加動態。當我將代碼切換到:
NSString* savedAgentName = [NSString stringWithFormat:@"%@", [thisfile substringWithRange:NSMakeRange(6,[thisfile length])]];
它崩潰我的應用程序。爲什麼?
這裏的代碼較大的塊:
//get saved agents
savedAgents = [[NSMutableArray alloc] initWithObjects:@"Select An Agent", nil];
for(int f=0; f<[rootcontents count]; f++) {
NSString* thisfile = [NSString stringWithFormat:@"%@", [rootcontents objectAtIndex:f]];
if ([thisfile rangeOfString:@"agent_"].location != NSNotFound) {
int thisfilelength = [thisfile length];
NSString* savedAgentName = [NSString stringWithFormat:@"%@", [thisfile substringWithRange:NSMakeRange(6,thisfilelength)]];
//NSLog(@"%@", savedAgentName);
[savedAgents addObject:savedAgentName];
}
}
感謝。
嘿,我沒有謝謝你的答案,但它已經幫了很多。 +1教我魚! – PruitIgoe 2011-01-29 10:25:47