[英]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];
}
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 = ...
(“自我”部分很重要)
並確保在dealloc中將其設置為nil。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.