NSString stringWithFormat上的仪器内存泄漏

Nit*_*ish 0 iphone nsstring ios

在我的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];

}  
Run Code Online (Sandbox Code Playgroud)

strLatitudestrLongitude是全局字符串.这绝对没问题.即使在分析应用程序时,我也没有任何内存泄漏.但是当我描述我的应用程序时,我收到了内存泄漏

strLatitude = [NSString stringWithFormat:@"%f",latitude];  
Run Code Online (Sandbox Code Playgroud)

strLongitude = [NSString stringWithFormat:@"%f", longitude];
Run Code Online (Sandbox Code Playgroud)

32个字节.

我该如何解决这个问题?

Ste*_*eve 5

你确定你看到了泄漏而不仅仅是分配吗?

如果你确实在这里发生泄漏,那么有一些潜在的嫌疑人:

你在用ARC吗?如果没有,这里有一些可能的问题:

  • 你是用dealloc发布的吗?

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

  • 如果你没有使用复制语义,并且你将这个字符串引用传递给其他人,并且他们没有正确地释放它,你也会得到这条线的回溯.

编辑:

(根据以下评论)

你应该意识到stringWithFormat:分配一个字符串并在其上排队自动释放...所以你需要将它保留在某个地方.

我以为你是在某个地方做这个,因为你没有得到"EXC_BAD_ACCESS" - 而是据说是泄密.

你不应该泄漏一个自动释放的对象,除非你把它保留在某个地方(因此假设).

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

我同意你应该使用这些字符串的属性.

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

在您的界面中:

@property (nonatomic, copy) NSString * strLatitude; 
Run Code Online (Sandbox Code Playgroud)

在您的实施中:

@synthesize strLatitude;
Run Code Online (Sandbox Code Playgroud)

分派:

self.strLatitude = ...
Run Code Online (Sandbox Code Playgroud)

("自我"部分很重要)

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

  • 史蒂夫不是我. (2认同)