【发布时间】:2011-10-16 06:02:11
【问题描述】:
好的,我知道有很多关于这个问题的问题,但是在阅读它们并尝试了这些方法之后,我的应用程序似乎仍然泄漏内存。我研究了Apple Guide on Memory Manegment 并阅读了值得注意的问题here、here 和here。我有一个解析 JSON 字符串然后将它们返回到NSMutableDictionary 的方法。我从返回方法对对象调用autorelease,然后在接收方法上调用retain(确保对象在池的下一个排水管上不释放)。然后当我完成它时我释放然后对象。但是它仍然泄漏。谁能看到我做错了什么?
返回方法
+ (NSMutableArray *)parseSpecialtyResult:(NSString *)json
{
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *dictionary = [parser objectWithString:json];
NSArray *jsonObjects = [dictionary valueForKey:@"Rows"];
NSMutableArray *jsonArray = [[NSMutableArray alloc] initWithCapacity:[jsonObjects count]];
//Storing objects
for (NSDictionary *dict in jsonObjects)
{
Specialty *specialty = [[Specialty alloc] init];
[specialty setName:[dict objectForKey:@"name"]];
[specialty setIdenity:[dict objectForKey:@"id"]];
[jsonArray addObject:specialty];
}
[parser release];
//Relinquish ownership of this object
return [jsonArray autorelease];
}
调用类
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
//This class will take the responsibility of the object's ownership
self.jsonArray = [[SpecialtyUrl parseSpecialtyResult:responseString] retain];
[tableView reloadData];
[responseString release];
}
- (void)dealloc
{
[super dealloc];
//No longer need the object
[jsonArray release];
NSLog(@"Ref count %i", [jsonArray retainCount]);
}
日志
Ref count 1
【问题讨论】:
-
还要注意,retainCount 对于查看这类事情几乎是一种无用的方法。在这里搜索它,你会看到 bbum 经常谈论它。 (而且他应该知道他在 Apple 工作的地方。)
-
通常retainCount 不显示真实信息。如果你想检查,你的内存在哪里增长,使用仪器。顺便说一句,你可以 1)释放你的专长,这可能会导致泄漏。
-
@Grant 感谢您提供的信息。我在分析器中仔细检查了它,并确认它正在泄漏:(
-
您是否从 Xcode 4 的 Product 菜单中运行了 Analyze?它实际上非常擅长查找并向您展示发生泄漏和过度发布的位置。
标签: iphone objective-c ios memory-management autorelease