2014-01-17 167 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中没有对象的情况,并尝试从空字符串中删除一个字符!