簡體   English   中英

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 可可 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伺服/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM