在我的 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];
}
strLatitude 和 strLongitude 是全局字符串。这绝对没问题。即使在分析应用程序时,我也没有发现任何内存泄漏。但是当我分析我的应用程序时,我在
处收到内存泄漏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 = ...
(“self.”部分很重要)
并确保在 dealloc 中将其设置为 nil。
关于iphone - NSString stringWithFormat 仪器内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9389274/