2011-01-27 169 views
3

我想使用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]; 
     } 
} 

感謝。

回答

7

substringWithRange:方法將(如文檔所述)引發NSRangeException「如果aRange的任何部分超出接收者的末尾」。

通過詢問從這個文件中的第6個位置開始的這個文件長度字符,您會越過字符串的末尾導致異常。

你需要減少6請求這樣的長度:

NSString *savedAgentName = [NSString stringWithFormat:@"%@", 
    [thisfile substringWithRange:NSMakeRange(6,thisfilelength-6)]]; 

順便說一句,這個代碼可以簡化爲:

NSString *savedAgentName = 
    [thisfile substringWithRange:NSMakeRange(6,thisfilelength-6)]; 


不過,既然你想整個來自某個索引的字符串的其餘部分,這可以通過使用substringFromIndex:來進一步簡化:

NSString *savedAgentName = [thisfile substringFromIndex:6]; 

還要注意,上面的所有代碼假定字符串至少有6個字符。爲了安全起見,在獲取子字符串之前檢查此文件的長度是否爲6或更大。如果長度小於6個字符,則可以將savedAgentName設置爲空白。

+1

嘿,我沒有謝謝你的答案,但它已經幫了很多。 +1教我魚! – PruitIgoe 2011-01-29 10:25:47