gpt4 book ai didi

ios - 保留其键的 NSMutableDictionary

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:18:27 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何创建一个保留而不是复制其键的 NSMutableDictionary。我已经实现了 -(NSUInteger)hash 和 -(id)isEqual: 对于我想要的键,我只是无法确定在回调中指定哪些选项。

CFDictionaryKeyCallBacks    keyCallbacks    = { 0, NULL, NULL, CFCopyDescription, CFEqual, NULL };


self.commonParents = (NSMutableDictionary*)CFBridgingRelease(CFDictionaryCreateMutable(nil, 0, &keyCallbacks, &kCFTypeDictionaryValueCallBacks));

上面的代码在 ARC 中使用对键的弱引用可以正常工作,但是如果我想要强引用怎么办?关键回调应该是什么样的?

最佳答案

tl;博士:

创建一个 CFDictionaryRef使用提供的默认回调函数。它会做你想做的。只是不要称它为 NSDictionary .


是的,您可以创建一个 CFDictionaryRef保留其 key 并且不复制它们。事实上,这是 CFDictionaryRef默认行为 .

CFDictionaryCreateMutable() 的文档说:

If the dictionary will contain only CFType objects, then pass a pointer to kCFTypeDictionaryKeyCallBacks as this parameter to use the default callback functions.

(因此,如果您只想将普通的 Objective-C 对象放入数组中,而不是像 void * 指针之类的随机对象,这就是您想要的)

以及 kCFTypeDictionaryKeyCallBacks 的文档说:

Predefined CFDictionaryKeyCallBacks structure containing a set of callbacks appropriate for use when the keys of a CFDictionary are all CFType-derived objects. The retain callback is CFRetain, the release callback is CFRelease, the copy callback is CFCopyDescription, the equal callback is CFEqual. Therefore, if you use a pointer to this constant when creating the dictionary, keys are automatically retained when added to the collection, and released when removed from the collection.

请注意 retain回调是 CFRetain() 而不是像 CFCopyObject 这样的东西(实际上并不存在)。

事实上,Core Foundation 没有“复制任何对象”的规范方法,这就是为什么像 CFStringCreateCopy 这样的函数, CFArrayCreateCopy , CGPathCreateCopy等存在。

因此,您可以像这样创建字典:

CFDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

现在你有了一个字典,它保留了它的键并且不复制它们。

我要把下面的部分用大写字母写出来,这样你就明白我要说的是什么了:

您创建的这本词典不是 NSDictionary .

是的,NSDictionaryCFDictionaryRef是免费桥接电话。但是类型转换这个 CFDictionaryRefNSDictionary会滥用桥接,因为 NSDictionary 中的这一行文档:

...a key can be any object (provided that it conforms to the NSCopying protocol—see below)

同样,-[NSMutableDictionary setObject:forKey:] 的文档明确地说:

The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol).

字典中的键不必符合 <NSCopying>并且不使用 -copyWithZone: 复制,这意味着您的字典不是 NSDictionary (或 NSMutableDictionary )。任何时候你看到 NSDictionary在代码中使用时,您应该提供键值映射,其中键被复制(不保留)。那就是 API 契约(Contract)。做任何其他事情都可能导致未定义的行为。

(一些对象将 -copy 覆盖为 return [self retain] 的事实是一个实现细节,与关于“什么是 NSDictionary ”的讨论无关。)

关于ios - 保留其键的 NSMutableDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15054903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com