NSRange在for循环中自行更改

时间:2014-06-18 00:18:25

标签: ios objective-c nsrange nsexception nsrangeexception

我有NSRange对象的NSDictionary,在数组中有索引的键。我试图使用这些范围中的每一个来创建更大字符串的子字符串,并将每个子字符串放在数组中。我基本上已经完成了这个,但NSRange神秘地改变了它在代码中的价值,导致它崩溃并引发异常。这是我的代码:

NSMutableArray*subStringArray = [[NSMutableArray alloc] init];
for(id key in aDict){
            NSRange* range = CFBridgingRetain([aDict objectForKey:key]);
            NSLog(@"This is a single range: %@",range);
            //Range is changed here somehow
            NSString* aSubString = [self.content substringWithRange:*range];
            NSLog(@"%@",aSubString);
            [subStringArray addObject:aSubString];
        }

我的日志输出如下所示:

This is a single range: NSRange: {1874, 72}
2014-06-17 20:07:30.100 testApp[8027:60b] *** Terminating app due to uncaught exception     
'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {4318599072, 4} out of bounds; string length 5562'

1 个答案:

答案 0 :(得分:3)

受欢迎的需求:)

您的代码的主要问题是您直接在字典中存储NSRange结构。你不能这样做。您必须将NSRange包装在NSValue中以将其存储在字典中。

要添加NSRange,您可以执行以下操作:

NSRange range = ... // some range
NSValue *value = [NSValue valueWithRange:range];
dict[someKey] = value;

然后您发布的代码变为:

for (id key in aDict) {
    NSValue *value = aDict[key];
    NSRange range = [value rangeValue];
    NSLog(@"This is a single range: %@",range);
    //Range is changed here somehow
    NSString* aSubString = [self.content substringWithRange:range];
    NSLog(@"%@",aSubString);
    [subStringArray addObject:aSubString];
}