简体   繁体   English

NsMutable数组保留计数

[英]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 我使用这些仪器在我的iPhone应用程序中查找泄漏,并且发现我的代码此行中存在泄漏

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

the property dataSource defined as retain. 属性dataSource定义为保留。 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]]; 无需使用alloc / init方法创建新数组,只需使用[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. 我建议选择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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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