Objective-C 类别中的重大泄漏
我创建了一个自定义 NSString 类别,它可以让我找到两个其他字符串之间的所有字符串。我现在遇到的问题是发现我的脚本中有很多 kB 泄漏。请参阅下面的代码:
#import "MyStringBetween.h"
@implementation NSString (MyStringBetween)
-(NSArray *)mystringBetween:(NSString *)aString and:(NSString *)bString;
{
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
NSArray *firstlist = [self componentsSeparatedByString:bString];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int y = 0; y < firstlist.count - 1 ; y++) {
NSString *firstObject = [firstlist objectAtIndex:y];
NSMutableArray *secondlist = [firstObject componentsSeparatedByString:aString];
if(secondlist.count > 1){
[finalArray addObject:[secondlist objectAtIndex:secondlist.count - 1]];
}
}
[autoreleasepool release];
return finalArray;
}
@end
我承认我不太擅长释放对象,但我相信 NSAutoreleasePool 会为我处理事情。
泄漏的行:
NSMutableArray *secondlist = [firstObject componentsSeparatedByString:aString];
手动释放 secondarylist 会引发异常。
提前致谢!
I created a custom NSString Category which lets me find all strings between two other strings. I'm now running into the problem of finding that there are a lot of kBs leaking from my script. Please see code below:
#import "MyStringBetween.h"
@implementation NSString (MyStringBetween)
-(NSArray *)mystringBetween:(NSString *)aString and:(NSString *)bString;
{
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
NSArray *firstlist = [self componentsSeparatedByString:bString];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int y = 0; y < firstlist.count - 1 ; y++) {
NSString *firstObject = [firstlist objectAtIndex:y];
NSMutableArray *secondlist = [firstObject componentsSeparatedByString:aString];
if(secondlist.count > 1){
[finalArray addObject:[secondlist objectAtIndex:secondlist.count - 1]];
}
}
[autoreleasepool release];
return finalArray;
}
@end
I admit that I'm not super good at releasing objects, but I had believed that the NSAutoreleasePool handled things for me.
The line that is leaking:
NSMutableArray *secondlist = [firstObject componentsSeparatedByString:aString];
Manually releasing secondlist raises an exception.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是泄漏的行:
而且泄漏并没有那么大(只是一个空的可变数组)。不过,还是不要这样做。
特别是,该行:
正在分配对空可变数组的引用。
另外,
FinalArray
应命名为finalArray
。No, this is the line that is leaking:
And it isn't that big of a leak (just an empty mutable array). Still, don't do that.
In particular, the line:
Is assigning over the reference to the empty mutable array.
Also
FinalArray
should be namedfinalArray
.FinalArray 泄漏。您应该在返回它之前自动释放它,但请确保在分配自动释放池之前或释放它之后执行此操作。
finalArray is leaking. You should autorelease it before returning it but make sure you do it either before allocating the autorelease pool or after releasing it.