Objective C - 两个使用相同值的字典,强弱

时间:2022-01-06 14:21:35

I'm new to objective c and I've got an interesting situation where I need two different NSDictionary objects that point to the same values. In that situation should I use strong or weak in the property declaration? Or should I do strong in one and weak in the other?

我是目标c的新手,我有一个有趣的情况,我需要两个不同的NSDictionary对象,指向相同的值。在那种情况下,我应该在财产声明中使用强弱吗?或者我应该做一个强者而弱者另一个?

In Game.m

@property (strong/weak, nonatomic) NSDictionary* answers1;

In User.m

@property(strong/weak, nonatomic) NSDictionary* answers2;

In both cases the key will be an integer, but the value will be an answer object of my own making. Both answers1 and answers2 will need to exists for roughly the same amount of time. When it comes time to get rid of one it'll be okay to get rid of the other.

在这两种情况下,键都是一个整数,但该值将是我自己制作的答案对象。答案1和答案2都需要存在大致相同的时间。当它摆脱一个时,它可以摆脱另一个。

3 个解决方案

#1


3  

Both should probably be strong. Each class should do its own memory management without having to worry about what other classes are doing. Therefore, each should keep its own strong reference.

两者都应该很强大。每个类都应该自己进行内存管理,而不必担心其他类正在做什么。因此,每个人都应该保持自己的强大参考。

#2


0  

Strong.

If either was weak, something else would need to maintain a reference to the dictionary in order to ensure it's existence. Weak references do not increment the ARC reference count so if there was a low memory warning for instance, your weak Dictionary would be deallocated.

如果其中任何一个很弱,那么其他东西需要维护对字典的引用以确保它的存在。弱引用不会增加ARC引用计数,因此如果存在低内存警告,则会释放弱字典。

#3


0  

In this case, the best would actually be copy. This way, in addition to retaining the dictionary, you will create an immutable copy of the one passed to you, ensuring the dictionary does not get modified from an outside influence (for example, passing a mutable dictionary which can later mutate).

在这种情况下,最好的实际上是复制。这样,除了保留字典之外,您还将创建传递给您的字典的不可变副本,从而确保字典不会受到外部影响的修改(例如,传递可以在以后变异的可变字典)。

#1


3  

Both should probably be strong. Each class should do its own memory management without having to worry about what other classes are doing. Therefore, each should keep its own strong reference.

两者都应该很强大。每个类都应该自己进行内存管理,而不必担心其他类正在做什么。因此,每个人都应该保持自己的强大参考。

#2


0  

Strong.

If either was weak, something else would need to maintain a reference to the dictionary in order to ensure it's existence. Weak references do not increment the ARC reference count so if there was a low memory warning for instance, your weak Dictionary would be deallocated.

如果其中任何一个很弱,那么其他东西需要维护对字典的引用以确保它的存在。弱引用不会增加ARC引用计数,因此如果存在低内存警告,则会释放弱字典。

#3


0  

In this case, the best would actually be copy. This way, in addition to retaining the dictionary, you will create an immutable copy of the one passed to you, ensuring the dictionary does not get modified from an outside influence (for example, passing a mutable dictionary which can later mutate).

在这种情况下,最好的实际上是复制。这样,除了保留字典之外,您还将创建传递给您的字典的不可变副本,从而确保字典不会受到外部影响的修改(例如,传递可以在以后变异的可变字典)。