iphone:如何解决 NSArray 内存泄漏?
我正在释放 NSArray 和 NSMutableArray 但它显示内存泄漏。而ZoneData代码是这样的
-(ZoneData*) initWithZoneName:(NSString *)zoneNameIn SdName:(NSString *)sdNameIn eCount:(NSString *)eCountIn iCount:(NSString *)iCountIn StandLat:(NSString *)standLatIn StandLong:(NSString *)standLongIn
{
self = [super init];
if (self)
{
zoneName = [zoneNameIn copy];
lsdName = [sdNameIn copy];
leCount = [eCountIn intValue];
liCount = [iCountIn intValue];
standLat = [standLatIn copy];
standLong = [standLongIn copy];
}
return self;
}
如何解决这个问题?
I am releasing NSArray and NSMutableArray but its show memory leak. while ZoneData code is like this
-(ZoneData*) initWithZoneName:(NSString *)zoneNameIn SdName:(NSString *)sdNameIn eCount:(NSString *)eCountIn iCount:(NSString *)iCountIn StandLat:(NSString *)standLatIn StandLong:(NSString *)standLongIn
{
self = [super init];
if (self)
{
zoneName = [zoneNameIn copy];
lsdName = [sdNameIn copy];
leCount = [eCountIn intValue];
liCount = [iCountIn intValue];
standLat = [standLatIn copy];
standLong = [standLongIn copy];
}
return self;
}
how to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你的实例变量。在您的
-init
中,您正确地将它们分配给数组中字符串的副本。但是,您还不需要在-dealloc
中释放它们。现在,您可能会问为什么泄漏工具会告诉您泄漏是您创建带有字符串的 NSArray 的位置而不是 init 方法的位置。原因是不可变对象的
-copy
被优化为除了将保留发送到self
之外不执行任何操作。因此,作为实例变量的那些副本实际上与-componentsSeparatedByString:
创建的对象相同The problem is your instance variables. In your
-init
, you are correctly assigning them to copies of the strings from the array. However, you need t also release them in-dealloc
.Now, you may be asking why the leaks tool is telling you the leaks are where you create the
NSArray
with the strings in it instead of the init method. The reason is that-copy
for immutable objects is optimised to do nothing except send retain toself
. So those copies you have as instance variables are in reality the same objects as was created by-componentsSeparatedByString:
componentsSeparatedByString:
返回一个自动释放的NSArray
。你不应该自己释放它,但最近的 NSAutoreleasePool 会为你做这件事。在第 61 行中,您过度释放了数组。如果您在执行循环时担心内存使用情况,可以在循环的每次迭代中清除自动释放的对象:
componentsSeparatedByString:
returns an autoreleasedNSArray
. You are not supposed to release that yourself, but the closestNSAutoreleasePool
will do that for you. In line 61 you are overreleasing the array.If you are concerned about the memory usage while performing the loop you can clear autoreleased objects in each iteration of the loop: