开发者

Memorymanagement when getting a NSMutableArray from NSObject class to UIViewController class

开发者 https://www.devze.com 2023-03-04 22:36 出处:网络
I have problem with the following code leaking memory... @property (nonatomic, retain) NSMutableArray *childrensArray;

I have problem with the following code leaking memory...

@property (nonatomic, retain) NSMutableArray *childrensArray;


-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"Connection finished loading.");  
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];

NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
childrensArray = [jsonData objectForKey:@"Children"];

// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadC开发者_运维问答hildren];

[connection release];
[responseData release];
[jsonString release];
[parser release]; 
}  

In the viewController the following also leaks memory...

@property (nonatomic, retain) NSMutableArray *childrensArray;


- (void)loadChildren {

// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];   

int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:@"%d", total]; 

[theTableView reloadData];
}   


You only release childrensArray when the instance is deallocated. You should also release the instance variable before setting it:

- (void)loadChildren {
    // Retrieve a array with dictionaries of children from ServiceGetChildren 
    [childrensArray release];
    childrensArray = [serviceGetChildren.childrensArray copy]; 
}

A better way would be to actually use your property:

- (void)loadChildren {
    // Retrieve a array with dictionaries of children from ServiceGetChildren 
    self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease]; 
}

(Note the autorelease)

This has the benefit of triggering KVO-Notifications should you ever use them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号