cocoa - 绑定(bind)枚举属性最简洁的方法是什么?

标签 cocoa cocoa-bindings binding nsmenu nsmenuitem

我有一个菜单,其中包含枚举中每个值的项目。

菜单:

[ ] Sort by Due Date
[ ] Sort by Priority
[√] Sort by Title

枚举:

typedef enum  CW_TASK_SORT_METHOD {
    CWTaskSortMethodDueDate,
    CWTaskSortMethodPriority,
    CWTaskSortMethodTitle
} CWTaskSortMethod;

属性:

@property(readwrite, assign) CWTaskSortMethod taskSortMethod;

最简洁的连接方法是什么?我有两个想法,但都令我不满意。

第一个想法:为每个值创建属性(sortMethodIsDueDatesetSortMethodIsDueDate: 等)这些属性将调用 setTaskSortMethod: 并调用 valueDidChange:@"sortMethodIsDueDate" 等。然后菜单项将绑定(bind)到这些属性。这看起来工作量很大。

第二个想法:将每个菜单项连接到 -(IBAction)updateSortMethod:(id)sender,然后它可以迭代菜单项并根据 sender 设置值。这种方法很好,直到 taskSortMethod 被不同的代码部分更改,此时需要添加代码以保持菜单与 taskSortMethod 同步。

我倾向于第一种方法,因为它在 V 和 C 之间有更好的分离。

还有更好的想法吗?

最佳答案

我认为你的第二个想法是正确的,但有一些事情需要考虑:

NSMenu/NSMenuItem 没有像 NSPopUpButton 这样的“所选项目”的概念。我会使用目标/操作机制来更改排序方法和菜单验证( Introduction to User Interface Validation ),甚至 NSMenu 委托(delegate)方法 -menu:updateItem:atIndex:shouldCancel: ( NSMenuDelegate Protocol Reference )来更新基于项目的状态关于 -taskSortMethod 的结果。

由于菜单项仅在显示时才需要更新(此机制为您所做的),因此当 -taskSortMethod 在其他地方更改时,您不必担心自己更新菜单项。

例如:

[sortByDueDateMenuItem setState: ([self taskSortMethod] == CWTaskSortMethodDueDate) ];

IMO,这比尝试过度设计绑定(bind)驱动的解决方案要干净得多。

关于cocoa - 绑定(bind)枚举属性最简洁的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1676421/

相关文章:

objective-c - 在视网膜显示器上用 Cocoa 进行像素完美的绘图——只做 floor() 将不再有效

cocoa - 将 TableView 绑定(bind)到字典数组

cocoa - NSArrayController,以编程方式创建 CoreData 实体,以及 KVO

swift : Why is my View Model with a binding not working with the Toggle in my View?

iphone - FMDB数据库WithPath : not writing to disk

objective-c - 连接 Action 有效。连接 socket 不

cocoa - Swift 和 Core Data 错误 : fatal error: use of unimplemented initializer 'init(entity:insertIntoManagedObjectContext:)'

cocoa - 如何验证通过 Cocoa Bindings 动态填充的菜单项

c# - XAML 中的数据绑定(bind)(多路绑定(bind)?)

wpf - WPF DataGrid问题: why the data output twice?