我知道我们可以从引用 -> 原始指针 -> 地址 ( usize) 进行转换,但是我们可以向后进行转换,特别是使用生命周期注释吗?例如,我有以下代码:
struct Name<'a> {
name: &'a str,
}
impl<'a> Name<'a> {
fn to_addr<'b>(&'b self) -> usize { /* ... */ }
fn from_addr<'b>(address: usize) -> &'b Name<'a> {
// assuming the address is valid,
// is this even possible to return an reference with both lifetimes?
}
}
Run Code Online (Sandbox Code Playgroud) 我注意到通过Instruments在NSCollectionView中发生内存泄漏。当我查找代码时,它显示下面的特定行:
collectionView.makeItem(withIdentifier: identifier, for: indexPath) as? DisplayableCellProtocol
Run Code Online (Sandbox Code Playgroud)
然后我在Xcode,内存调试器中查看了它,发现有一些未引用的项目导致了泄漏。但是,并非由创建的所有项目都在makeItem泄漏,其中有些是正常的,但有些甚至没有显示。
那正常吗,其他人也有同样的问题吗?有谁知道如何正确解决这个问题?这与使用xib设计项目视图有关吗?
以下是一些有助于理解这种情况的代码:
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let data = datasource[indexPath.item]
let identifier: String = "ServiceCell"
// Next line is where the leak occurs
guard let cell = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: identifier), for: indexPath) as? ServiceCell else {
return ServiceCell(nibName: NSNib.Name("ServiceCell.xib"), bundle: Bundle.main)
}
cell.iconView.image = data.icon
cell.serviceLabel.stringValue = data.name
cell.introLabel.stringValue = data.content
cell.highlighted = false
return cell
}
Run Code Online (Sandbox Code Playgroud)
ServiceCell的定义是:
class ServiceCell: NSCollectionViewItem { …Run Code Online (Sandbox Code Playgroud) 我试图Text在所有可见行的当前索引列表中为每个可见(在屏幕边界内)行放置一个。
我这里有一个例子。如果我有一个列表一次显示 3 行,并且最初我希望它显示如下:
___|___
A | 0
B | 1
C | 2
-------
Run Code Online (Sandbox Code Playgroud)
如果我向下滚动列表,并且 A 退出屏幕,那么它就像
___|___
B | 0
C | 1
D | 2
-------
Run Code Online (Sandbox Code Playgroud)
知道我该怎么做吗?
此外,我曾经使用UITableView.visibleCells来获取屏幕上的可见单元格,但我在 SwiftUI 中找不到类似的东西。我究竟如何才能在 SwiftUI 中仅提供索引的列表中获得可见行?
希望有人能指引我到正确的地方。非常感谢!
当从窗口检测到 keyUp 时,我试图更改状态值。但是,它似乎对我不起作用。这是我的代码
/// Window
class Window: NSWindow {
override func keyUp(with event: NSEvent) {
(contentView as! NSHostingView<ContentView>).rootView.keyPressed(with: event)
}
}
/// ContentView
struct ContentView {
@State var index: Int = 0
var body: some View { ... }
func keyPressed(with event: NSEvent) {
self.index = self.index + 1
}
}
Run Code Online (Sandbox Code Playgroud)
我用调试器测试了一下,显然keyPressed调用成功,但是索引设置不正确。有谁知道为什么?或者在 macOS 的 SwiftUI 中听键盘的正确策略是什么?
ios ×2
macos ×2
swift ×2
swiftui ×2
memory-leaks ×1
rust ×1
storyboard ×1
swiftui-list ×1
unsafe ×1
xcode ×1