我正在解析一个xml文件,我一直试图去除currentElementValue中的空白字符,因为它搞乱了一些事情.
我可以在输出窗口中看到有几个回车符和制表符
(gdb) po string
Keep the arms on the side, and lift your leg.
(gdb) po currentElementValue
Keep the arms on the side, and lift your leg.
(gdb)
Run Code Online (Sandbox Code Playgroud)
这是我的foundCharacters函数,我一直试图使用stringByTrimmingCharactersInSet但遗憾的是没有成功.
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
{
[currentElementValue appendString:string];
currentElementValue = [currentElementValue stringByTrimmingCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
NSString *instructions = @"instructions";
[directions setValue:string forKey:instructions]; //mm
[appDelegate.directions setValue:string forKey:instructions];
//[appDelegate.directions setObject:string forKey:currentElementValue];
// [appDelegate
}
}
Run Code Online (Sandbox Code Playgroud)
我一直收到这个错误***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'尝试用appendString改变不可变对象:'这很奇怪,因为我的currentElementValue是一个NSMutableString ..那么出了什么问题?有没有人有线索或想法?
让我们一步一步,找到你的bug,并解决内存泄漏问题:
首先,创建一个NSMutableString.大.(+1保留计数)
然后将另一个字符串附加到NSMutableString上.没关系.(仍然+1保留计数).
然后你修剪newlineCharacterSet,它返回一个自动释放的NSString.由于此对象与原始对象不同,因此您泄漏了原始对象(因为它具有+1保留计数而您不再有指向它的指针),并且您现在有一个不可变的NSString可以引导.这意味着下次调用此方法时,您将尝试将一个字符串附加到NSString上,这将抛出"无法改变不可变对象"异常.
以下是解决此问题的快捷方法:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
{
[currentElementValue appendString:string];
NSString *trimmedString = [currentElementValue stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
[currentElementValue setString:trimmedString];
NSString *instructions = @"instructions";
[directions setValue:string forKey:instructions]; //mm
[appDelegate.directions setValue:string forKey:instructions];
//[appDelegate.directions setObject:string forKey:currentElementValue];
// [appDelegate
}
}
Run Code Online (Sandbox Code Playgroud)
(将修剪后的字符串保存到另一个变量,然后使用NSMutableString的setString:方法传入内容,但不会丢失指向NSMutableString的指针)