简体   繁体   English

在NSOutlineView中使用Swift结构

[英]Using a Swift struct in an NSOutlineView

I'm trying to populate an NSOutlineView with Swift structs as its items. 我正在尝试使用Swift结构填充NSOutlineView This works, except for the row(forItem:) method, which always returns -1. row(forItem:)方法始终返回-1之外,此方法均有效。 I've made sure my struct conforms to Equatable and I implemented an isEqual function. 我确保我的结构符合Equatable并实现了isEqual函数。 Still the NSOutlineView can not find the row for any item. 仍然NSOutlineView找不到任何项目的行。

If I convert my struct to a class ( not derived from NSObject), it all works. 如果我将结构转换为类( 不是从NSObject派生的),则一切正常。 Even without conforming to Equatable or implementing any isEqual functions. 即使不遵守Equatable或实现任何isEqual函数。

I thought classes and structs in Swift are basically the same except one being a reference type and the other a value type. 我认为Swift中的类和结构基本上是相同的,除了一个是引用类型,另一个是值类型。

What do I need to implement to use Swift structs as items in an NSOutlineView ? 我需要实现什么才能将Swift结构用作NSOutlineView项目?

Someone posted a similar question on the Apple Developer Forum. 有人在苹果开发者论坛上发布了类似的问题

NSOutlineView doesn't use Equatable when identifying an item, it uses the reference pointer to the item. NSOutlineView在标识项目时不使用Equatable,而是使用指向项目的引用指针。 In Swift, structs are always passed by value (and not passed by reference) so the outline view will never recognize that the item you're passing is the same. 在Swift中,结构总是按值传递(而不是按引用传递),因此大纲视图将永远不会识别出您传递的项目是相同的。 Switching your struct to a class fixes the issue because Swift uses pass by reference for classes. 将结构切换到类可以解决此问题,因为Swift使用按引用传递类。

Unfortunately, there's no way to use Structs as items to work with NSOutlineView and you will need to use a Class. 不幸的是,没有办法将Structs用作与NSOutlineView一起使用的项目,并且您将需要使用Class。

Read this answer for more details about how Swift uses pass by reference vs. pass by value. 请阅读此答案,以获取有关Swift如何使用按引用传递和按值传递的更多详细信息。

Release notes for macOS 10.14 point that if a Swift value type conforms to both Equatable and Hashable protocols, the NSOutlineView will successfully work with that value type. macOS 10.14的发行说明指出,如果Swift值类型同时符合Equatable和Hashable协议,则NSOutlineView将成功使用该值类型。

But if you build against an older SDK, the value types won't work with the NSOutlineView indeed. 但是,如果您使用较旧的SDK进行构建,则值类型实际上不适用于NSOutlineView。

您可以通过简单地查看所有行并返回相等索引来覆盖子类中的方法row(forItem item: Any?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM