简体   繁体   中英

NsMutable array retain count

i used the instruments to find leaks in my iphone app and i found that i have leak in this line in my code

tableViewController.dataSource = [[NSMutableArray alloc] initWithArray:[subjects_dic allKeys]];

the property dataSource defined as retain. is this a mistake ?!

Break it up:

NSMutableArray *mutArray = [[NSMutableArray alloc] initWithArray:[subjects_dic allKeys]];
[tableViewController setDataSource:mutArray];
[mutArray release];

It's the same pattern you use for creating, pushing, and releasing Views from the Navigation Controller.

If you specify retain in your property declaration, then anything you assign to that property will be retained.

So in your example, you have two options:

  1. Instead of creating a new array with the alloc/init approach, you can simply use [NSMutableArray arrayWithArray:[subjects_dic allKeys]];

  2. Release the property once after setting it. This option isn't as good an idea, as it may cause a crash if the property's memory management is changed in the future and this release is forgotten about.

I'd recommend option 1.

Another alternative:

// mutableCopy implicitly retains the array returned by allKeys
NSMutableArray *mutArray = [[subjects_dic allKeys] mutableCopy];
[tableViewController setDataSource:mutArray]; // @property dataSource retains mutArray
[mutArray release];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM