ios 移除html标签,ios - Remove HTML Tags from an NSString on the iPhone - Stack Overflow

本文介绍了一种使用Objective-C从字符串中去除HTML标记的方法,并通过@autoreleasepool确保了临时对象的有效管理,从而减少内存占用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have following the accepted answer by m.kocikowski and modified is slightly to make use of an autoreleasepool to cleanup all of the temporary strings that are created by stringByReplacingCharactersInRange

In the comment for this method it states, /* Replace characters in range with the specified string, returning new string.

*/

So, depending on the length of your XML you may be creating a huge pile of new autorelease strings which are not cleaned up until the end of the next @autoreleasepool. If you are unsure when that may happen or if a user action could repeatedly trigger many calls to this method before then you can just wrap this up in an @autoreleasepool. These can even be nested and used within loops where possible.

Apple's reference on @autoreleasepool states this... "If you write a loop that creates many temporary objects. You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application." I have not used it in the loop, but at least this method cleans up after itself now.

- (NSString *) stringByStrippingHTML {

NSString *retVal;

@autoreleasepool {

NSRange r;

NSString *s = [[self copy] autorelease];

while ((r = [s rangeOfString:@"]+>" options:NSRegularExpressionSearch]).location != NSNotFound) {

s = [s stringByReplacingCharactersInRange:r withString:@""];

}

retVal = [s copy];

}

// pool is drained, release s and all temp

// strings created by stringByReplacingCharactersInRange

return retVal;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值