AsyncSocket and Notifications - memory leak
I have a memory leak in the following scenario. I read data at every 30 seconds, use SBJSONParser to transform it to a dictionary, add a notification and after that use the data to bind it to a tableview:
// Read data and send notification
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *content = [[NSString alloc] initWithData:[data subDataWithRange:NSMakeRange(0, [data length] - 2)] encoding: NSUTF8StringEncoding];
// Line where leaks appear
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]];
[content release];
// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict];
[dict release];
}
On a CustomViewController I have the observer:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindData) name:@"BindData" object:nil];
and the bindData method:
-(vo开发者_Go百科id)bindData:(NSNotification*)notification
{
NSAutoreleasePool* pool = [[NSAutoReleasePool alloc] init];
NSMutableArray* customers = [notification.userInfo objectForKey:@"Customers"];
for (NSDictionary* customer in customers)
{
Company* company = [[Company alloc] init];
company.name = [customer objectForKey:@"CompanyName"];
NSLog(@"Company name = %@", company.name);
[company release];
}
[pool drain];
}
The problem is: when I set company.name = something from that dictionary, I get a memory leak on the line: NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]]; which keeps increasing since I'm reading at every 30 seconds.
I appreciate any help you can give. Thanks.
dict
is leaking because you are using alloc
and init
(thus increasing its retain count by 1), but never releasing it. Since the dictionary will no longer be needed after the notification has been posted, you can safely release it on the following line, like so:
// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict]
[dict release];
See the Memory Management Programming Guide for more details.
精彩评论