Rust Cocoa - 如何制作 NSDictionary?

Rust Cocoa - How to make an NSDictionary?

我一直在阅读,试图理解它。您可以在此处看到 dictionaryWithObjects:objects 接受对象和键的数组:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:keys
                                                         count:count];

https://developer.apple.com/documentation/foundation/nsdictionary#overview


但是initWithObjectsAndKeys_只有一个对象用于输入? ‍♂️

unsafe fn initWithObjectsAndKeys_(self, firstObject: *mut Object) -> *mut Object

https://docs.rs/cocoa/0.24.0/cocoa/foundation/trait.NSDictionary.html#tymethod.initWithObjectsAndKeys_

许多 Rust cocoa API 是底层 Objective-C API 的直接包装器,例如 initWithObjectsAndKeys:https://developer.apple.com/documentation/foundation/nsdictionary/1574190-initwithobjectsandkeys?language=objc。调用者应将指针传递给包含字典的交替值和键元素的空终止数组的第一个元素。

在 Objective C 中,您这样调用 initWithObjectsAndKeys

NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                    @"Value1", @"Key1",
                                    @"Value2", @"Key2",
                                    @"Value3", @"Key3",
                                    nil, nil
];

(从技术上讲,一个 nil 就足够了,但我发现它缺乏对称性,所以我放了两个 :-P)

这是一个可变参数函数,可以接受多个参数。

恐怕我对 Rust 的了解不够,不知道它是否能以同样的方式处理事情。

当然,在从此处的出色答案中学习如何做到这一点之后(以及在发布此问题之前,搜索存储库、所有 GitHub 和网络搜索了一段未公开的时间),我在@Josh Matthews servo/core-foundation-rs 库的测试中找到了一个例子:

let mkstr = |s| unsafe { NSString::alloc(nil).init_str(s) };
let keys = vec!["a", "b", "c", "d", "e", "f"];
let objects = vec!["1", "2", "3", "4", "5", "6"];

unsafe {
               
  let keys_raw_vec = keys.clone().into_iter().map(&mkstr).collect::<Vec<_>>();
  let objs_raw_vec = objects.clone().into_iter().map(&mkstr).collect::<Vec<_>>();

  let keys_array = NSArray::arrayWithObjects(nil, &keys_raw_vec);
  let objs_array = NSArray::arrayWithObjects(nil, &objs_raw_vec);

  let dict = NSDictionary::dictionaryWithObjects_forKeys_(nil, objs_array, keys_array);
}

来自https://github.com/servo/core-foundation-rs/blob/355740417e69d3b1a8d909f84d91a6618c9721cc/cocoa-foundation/tests/foundation.rs#L145