【问题标题】:Metal Device (MTLDevice) variable becomes nil after initializationMetal Device (MTLDevice) 变量在初始化后变为 nil
【发布时间】:2019-09-25 17:54:43
【问题描述】:

我的 Metal Swift (iOS/MacOS) 项目中有一个渲染器类,它是一个 MTKViewDelegate。我使用 MTLCreateSystemDefaultDevice() 提取 MTLDevice,但是在初始化之后,它变成了 nil?我想知道我是否在这里错过了 Swift 或 Metal 的一个怪癖。代码大致是这样的,

class Renderer: NSObject, MTKViewDelegate {

    var device: MTLDevice!
​
    init(metalView: MTKView) {
        guard let device = MTLCreateSystemDefaultDevice() else
        {
            fatalError("GPU not available")
        }
​        metalView.device = device
        if device != nil {
            print (“device not nil”)
        }
    }
​
    func draw(in view: MTKView) {
        if device == nil {
            print (“device is nil here”)
        }
    }
}

在我的 ViewController 我做

guard let metalView = view as? MTKView else {
   fatalError("Metal View not setup")
}
renderer = Renderer(metalView: metalView)

我看到的是:

device not nil
device is nil here
device is nil here
device is nil here
device is nil here

每次绘制调用时为 60hz

编辑:编辑代码以明确设备实际上被分配给全局范围 (metalView) 中的变量。

【问题讨论】:

    标签: ios swift macos metal


    【解决方案1】:

    根据您的代码,您没有将本地设备分配给隐式解包的全局设备变量。将本地设备分配给全局设备以解决问题。

    guard let device = MTLCreateSystemDefaultDevice() else
            {
                fatalError("GPU not available")
            }
    self.device = device
    

    【讨论】:

    • 对不起,我愿意,就那样做。我刚刚编辑了该行以使其简洁(我已将其放回原处)。请注意设备如何保存为 metalview 变量的一部分。我希望这足以让全局范围变量保持活动状态?
    • 据我所知,您正在将设备变量分配给 MTKView 实例。但是绘制函数是在渲染时调用的吗?如果是这样,您正在尝试访问不同的设备实例。
    • @pj_mukh 请检查上述评论。
    • 知道了!这就是解决方法,我认为“设备”与“self.device”相同。我错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2017-04-13
    • 2013-04-05
    • 2020-12-26
    • 2012-06-15
    • 2012-10-19
    • 2016-11-03
    相关资源
    最近更新 更多