【发布时间】:2012-09-21 02:33:09
【问题描述】:
编辑:我在项目中使用 ARC
我像这样从 plist 加载注释:
[NSThread detachNewThreadSelector:@selector(loadPList) toTarget:self withObject:nil];
...
- (void) loadPList
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:@"test.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; // memory leak here
NSMutableArray *annotations = [[NSMutableArray alloc]init];
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray * annotationsToRemove = [ mapView.annotations mutableCopy ] ;
[ annotationsToRemove removeObject:mapView.userLocation ] ;
[ mapView removeAnnotations:annotationsToRemove ] ;
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"blackKey"])
{
NSArray *ann = [dict objectForKey:@"Black"];
for(int i = 0; i < [ann count]; i++) {
NSString *coordinates = [[ann objectAtIndex:i] objectForKey:@"Coordinates"];
double realLatitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:1] doubleValue];
double realLongitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:0] doubleValue];
MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);
myAnnotation.title = [[ann objectAtIndex:i] objectForKey:@"Name"];
myAnnotation.subtitle = [[ann objectAtIndex:i] objectForKey:@"Address"];
myAnnotation.icon = [[ann objectAtIndex:0] objectForKey:@"Icon"];
[mapView addAnnotation:myAnnotation];
[annotations addObject:myAnnotation];
}
}
});
}
一切正常,但内存泄漏工具显示泄漏。
【问题讨论】:
-
唯一可能泄漏的方法是如果没有激活的自动释放池。检查您的控制台是否有“刚刚泄漏”的消息。
-
我认为这是泄漏,因为我将此代码作为新线程运行 [NSThread detachNewThreadSelector:@selector(loadPList) toTarget:self withObject:nil];
-
如果你在自己的线程中运行它,你需要添加一个自动释放池。
-
(我假设您使用的是 ARC,因为您指定了“自动引用计数”标签。)
-
好的..我需要把@autoreleasepool { ... }放在哪里?
标签: ios memory-leaks plist automatic-ref-counting nsdictionary