繁体   English   中英

仪器在NSString stringWithFormat处发生内存泄漏

[英]Memory leak on instrument at NSString stringWithFormat

在我的appDelegate我正在使用LocationManager

- (void)locationManager: (CLLocationManager *)manager
    didUpdateToLocation: (CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    float latitude = newLocation.coordinate.latitude;
     strLatitude = [NSString stringWithFormat:@"%f",latitude];
    float longitude = newLocation.coordinate.longitude;
    strLongitude = [NSString stringWithFormat:@"%f", longitude];
    [self CheckOperation];

}  

strLatitudestrLongitude是全局字符串。 绝对好 即使在分析应用程序时,我也不会遇到任何内存泄漏。 但是,当我分析我的应用程序时,我在以下位置收到内存泄漏

strLatitude = [NSString stringWithFormat:@"%f",latitude];  

strLongitude = [NSString stringWithFormat:@"%f", longitude];

32个字节

我该如何解决?

您确定您看到的是泄漏,而不仅仅是分配?

如果您确实在此处泄漏,则可能有一些潜在的嫌疑人:

您在使用ARC吗? 如果没有,则可能存在一些问题:

  • 您要在dealloc中释放它吗?

  • 如果此方法多次运行,则在重新分配它之前不会释放最后一个值。

  • 如果您没有使用复制语义,并且正在将该字符串引用传递给其他人,并且他们没有适当地释放它,那么您还将获得对这一行的回溯。

编辑:

(根据下面的评论)

您应该意识到stringWithFormat:正在分配一个字符串并对其进行自动释放...因此您需要将其保留在某个地方。

我以为您在某个地方这样做是因为您没有得到“ EXC_BAD_ACCESS”-而是应该是泄漏。

除非您将自动释放的对象保留在某处(因此假设),否则不应泄漏该对象。

鉴于您需要将其保留在某个地方,我的上述建议是有效的-每个保留都需要一个匹配的版本。

我同意您应该对这些字符串使用属性。

转换它们很简单-并为您处理很多事情。

在您的界面中:

@property (nonatomic, copy) NSString * strLatitude; 

在您的实施中:

@synthesize strLatitude;

分派:

self.strLatitude = ...

(“自我”部分很重要)

并确保在dealloc中将其设置为nil。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM