gpt4 book ai didi

objective-c - 在嵌套作用域中将委托(delegate)分配给 NSOpenPanel 会导致 EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-11-30 10:04:52 24 4
gpt4 key购买 nike

考虑以下简化的代码示例。它在 Swift 中呈现,但同样的行为也发生在 Objective-c 中。

import Foundation
import Cocoa
class MainWindow : NSWindow {
@IBAction func onClick_openFile(sender : AnyObject?) {
let path = runOpenPanel(false);
NSLog(path as String)
}

@IBAction func onClick_crashyByeBye(sender : AnyObject?) {
let path = runOpenPanel(true);
NSLog(path as String)
}

private func runOpenPanel(useCrashyDelegate : Bool) -> NSString {
let openPanel = NSOpenPanel.init()
openPanel.canChooseDirectories = false
openPanel.canChooseFiles = true
openPanel.allowsMultipleSelection = false

let safeDelegate = MyOpenPanelDelegate.init() //same scope as openPanel.runModal()--works fine
if (useCrashyDelegate) {
let crashyDelegate = MyOpenPanelDelegate.init() //falls out of scope before openPanel.runModal() and crashes
openPanel.delegate = crashyDelegate
} else {
openPanel.delegate = safeDelegate
}

if (openPanel.runModal() == NSFileHandlingPanelOKButton && openPanel.URLs.count == 1) {
return openPanel.URLs[0].path!
}

return ""
}
}

class MyOpenPanelDelegate : NSObject, NSOpenSavePanelDelegate {
func panel(sender: AnyObject, shouldEnableURL url: NSURL) -> Bool {
var isDir : ObjCBool = false
if (NSFileManager.defaultManager().fileExistsAtPath(url.path!, isDirectory: &isDir)) {
return isDir || (url.path! as NSString).lastPathComponent.lowercaseString == "foo.txt"
}
return false
}
}

runOpenPaneluseCrashyDelegate 参数为 true 时,crashyDelegate 会在嵌套作用域中实例化,并在调用 openPanel.runModal()。由于打开的面板将 crashyDelegate 指定为其委托(delegate),因此我预计crashyDelegate 的引用计数会增加。但是,当 useCrashyDelegate 为 true 时,应用程序会崩溃并显示 EXC_BAD_ACCESS。如果 useCrashyDelegate 为 false,则将在与调用 openPanel.runModal() 的调用相同的作用域中实例化的 safeDelegate 分配给 open面板,并且没有 EXC_BAD_ACCESS

这让我相信 NSOpenPanel 不会增加其委托(delegate)的引用计数。这是预期的行为,还是可能是一个错误?

最佳答案

This is leading me to believe that NSOpenPanel is not incrementing its delegate's reference count. Is this the expected behavior, or might this be a bug?

这是预料之中的。检查属性的类型,你会看到它是 assign (Objective-C) 或 unsafe (Swift),不保留强引用。这是 Cocoa 代表的常见设计模式。

HTH

关于objective-c - 在嵌套作用域中将委托(delegate)分配给 NSOpenPanel 会导致 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com