2014-01-17 197 views
1

這一個適用於ios模擬器,但不適用於我的iphone設備。爲什麼?deleteCharactersInRange:範圍或索引超出範圍'

NSMutableString *categoryList = [NSMutableString string]; 
for (NSArray *category in self.storedCategories) { 
    [categoryList appendString:[category valueForKey:@"value"]]; 
    [categoryList appendString:@","]; 
} 
[categoryList deleteCharactersInRange:NSMakeRange([categoryList length]-1, 1)] 

2014-01-17 19:41:58.572 someapp[14586:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString deleteCharactersInRange:]: Range or index out of bounds' 
*** First throw call stack: 
(0x2de38f4b 0x382796af 0x2de38e8d 0x2ddfd88f 0x98419 0x305e0713 0x305e06b3 0x305e0691 0x305cc11f 0x305e0107 0x305dfdd9 0x305dae65 0x305b079d 0x305aefa3 0x2de04183 0x2de03653 0x2de01e47 0x2dd6cc27 0x2dd6ca0b 0x32a93283 0x30610049 0x995ed 0x38781ab7) 
libc++abi.dylib: terminating with uncaught exception of type NSException 
(lldb) 

回答

2

如果self.storedCategories爲零或爲空,那麼你將嘗試從一個空字符串中刪除字符。在修剪/刪除之前,您應該始終檢查字符串的長度。

1

看起來有趣的是,你的應用程序在實際設備上而不是在模擬器上崩潰。我建議你實際上由與此更換

[categoryList appendString:@","]; 

重新設計的實現:

if(![[self.storedCategories lastObject] isEqual:category]) { 
    [categoryList appendString:@","]; 
} 

這將防止末(添加逗號這就是我假設你正在嘗試使用deleteCharactersInRange:方法),它還將處理self.storedCategories中沒有對象的情況,並嘗試從空字符串中刪除一個字符!