如何正确使用NSPopUpButton

Bru*_*ira 3 cocoa objective-c nsdictionary nspopupbutton nsstringencoding

我有一个NSPopUpButton,我想用它来选择打开文件的文本编码.

我已经有了一些如何实现这一点的想法,但是当我开始学习Objective-C和Cocoa时,我几乎可以肯定有更好的方法可以实现我想要的.

我需要一个NSString,其中包含编码名称和相关的NSStringEncoding值.

我曾想过创建一个表示编码(名称和值)的类,并且有一个NSArray,其中包含这种类型的对象,然后使用数组的内容填充NSPopUpButton,但我认为应该有更好的方法.

我对NSDictionary类不是很熟悉,但我怀疑应该让事情变得更容易.

有人可以给我一个暗示吗?

Fra*_*ank 6

使用编码作为值创建字典,并将NSPopUpButton的名称创建为键

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
NSNumber numberWithLong:NSASCIIStringEncoding], @"ASCII", 
[NSNumber numberWithLong:NSUnicodeStringEncoding], @"Unicode", nil];
Run Code Online (Sandbox Code Playgroud)

然后将它们添加到NSPopUpButton中

[myPopUpButton addItemsWithTitles:[dict allKeys]]
Run Code Online (Sandbox Code Playgroud)

然后获取用户选择的编码

[dict objectForKey:[myPopUpButton titleOfSelectedItem]]
Run Code Online (Sandbox Code Playgroud)

注意:您需要将字符串编码枚举包装在对象中,例如NSValue或NSNumber.