我一直在四处阅读试图理解它。你可以在这里看到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。调用方应传递指向以 null 结尾的数组的第一个元素的指针,该数组包含字典的交替值和键元素。
在 Objective C 中,您像这样调用initWithObjectsAndKeys
:
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
@"Value1", @"Key1",
@"Value2", @"Key2",
@"Value3", @"Key3",
nil, nil
];
(从技术上讲,一个 nil 就足够了,但我发现它缺乏对称性,所以我放了两个 :-P)
这是一个可变参数函数,可以接受多个参数。
恐怕我对 Rust 的了解还不够多,无法知道它是否可以以同样的方式处理事情。
当然,在从这里的精彩答案中学会了如何做到这一点之后(以及在发布这个问题之前,搜索存储库、所有 GitHub 和 Web 的时间未公开),我在 Matthews 伺服/核心基础-rs 库@Josh的测试中找到了一个示例:
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