为什么从 NSString 中删除字符时出现错误?
在我的代码中,我尝试加载 ROBOTS.TXT 文件,然后通过“Disallow”字符串过滤它们,然后如果该行有“Disallow string”,则删除该字符串并返回行的其余部分。
这是 ROBOTS.TXT 的示例
用户代理:*
禁止:/搜索
禁止:/groups
禁止:/图片
禁止:/目录
允许:/catalogs/about
禁止:/目录
禁止:/新闻
允许:/news/directory
这是我的代码:
NSRange range;
NSURL *url=[NSURL URLWithString:@"http://www.google.com/robots.txt"];
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [content componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *robots=[[[NSMutableArray alloc] init] autorelease];
NSMutableString *line= [[[NSMutableString alloc] init] autorelease];
for(line in parsed){
range=[line rangeOfString:@"Disallow"];
if (range.location != NSNotFound) {
[line deleteCharactersInRange: NSMakeRange(1,9 )];
[robots addObject:line];
}
}
这是错误:
* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试改变不可变的” 带有deleteCharactersInRange的对象:'
here in my code i am trying to load a ROBOTS.TXT file and then filter them by "Disallow" string, then if that line has "Disallow string" delete this string and return the rest of line.
here is a sample of ROBOTS.TXT
User-agent: *
Disallow:/search
Disallow: /groups
Disallow: /images
Disallow: /catalogs
Allow: /catalogs/about
Disallow: /catalogues
Disallow: /news
Allow: /news/directory
and here is the code that i have :
NSRange range;
NSURL *url=[NSURL URLWithString:@"http://www.google.com/robots.txt"];
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [content componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *robots=[[[NSMutableArray alloc] init] autorelease];
NSMutableString *line= [[[NSMutableString alloc] init] autorelease];
for(line in parsed){
range=[line rangeOfString:@"Disallow"];
if (range.location != NSNotFound) {
[line deleteCharactersInRange: NSMakeRange(1,9 )];
[robots addObject:line];
}
}
and here is the error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable
object with deleteCharactersInRange:'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
for(line in parsed)
中的变量line
是不可变的,因为 for-in 语句构造返回 NSString。可能你需要的是:
The variable
line
infor(line in parsed)
is immutable because an NSString is returned by the for-in statement construct.Probably what you need:
ComponentsSeparatedByCharactersInSet 方法返回 NSString 的 NSArray。 NSString 是不可变的。您将 line 声明为 NSMutableString,但分配给 line 的对象仍然是 NSString。
The method componentsSeparatedByCharactersInSet returns an NSArray of NSString. NSString is immutable. You are declaring line as an NSMutableString, but the object that gets assigned to line is still an NSString.