简体   繁体   English

目标C-NSDictionary保留物件问题

[英]Objective c - NSDictionary retaining objects issue

I'll try to explain myself, I have an object Person and a singleton object PeopleManager that has a NSDictionary *_people . 我会尽力解释我自己,我有一个对象Person和单身对象PeopleManager具有NSDictionary *_people
_people is a dictionary that holds Person objects with the personId as key. _people是一个字典,其中包含以personId为键的Person对象。

When a person is created I add it ( self ) to the _people dictionary (in the Person init method) 创建人员后,我将其( self )添加到_people字典中(在Person init方法中)

The people dictionary should hold the person object until the person is dealloc, but the problem is that if I alloc the person somewhere in my code and then release it, it won't get dealloc because PeopleManager still holds it in the _people dictionary. 人员字典应该保留人员对象,直到人员被PeopleManager为止,但是问题是,如果我在代码中的某个地方PeopleManager人员然后释放它,则它不会被PeopleManager因为PeopleManager仍将其保存在_people词典中。

Really the problem is that the _people dictionary retain the person, if it was possible to have an assign dictionary it would be great, but I know it's not possible. 真正的问题是_people字典保留了这个人,如果有可能拥有一个assign字典,那就太好了,但是我知道这是不可能的。

What can I do to solve this? 我该怎么解决?

The dictionary must retain person because it is using it. 字典必须保留人,因为它正在使用它。 If this did not happen, the dictionary could not be guaranteed that it's objects were always still alive. 如果这没有发生,则无法保证字典中的对象始终处于活动状态。

When you release Person, such that you no longer need it at all and expect it to be dealloc'd, remove it from the dictionary via [NSMutableDictionary -removeObjectForKey:] (and thus decrementing the retain count). 当您释放Person时,不再需要它并希望将其取消分配,请通过[NSMutableDictionary -removeObjectForKey:]从字典中将其删除(从而减少保留计数)。 This will require use of NSMutableDictionary though because you cannot remove objects from a NSDictionary. 但是,这将需要使用NSMutableDictionary,因为您无法从NSDictionary中删除对象。

如果您使用NSDictionary的可变对象,则可以使用简单的-removeObjectForKey:删除不再使用的对象-removeObjectForKey:

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

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