[英]Swift Delegate in own class
I am currently trying to write my first Swift Mac application. 我目前正在尝试编写我的第一个Swift Mac应用程序。 Currently I have hard times refactoring some code into another class.
目前,我很难将一些代码重构为另一个类。
Current Status: 当前状态:
import Cocoa
class TestClass: NSObject, NSTextStorageDelegate {
@IBOutlet var codeTextView: NSTextView!
var syntaxParser:TRexSyntaxKitParser?
var textStorage : NSTextStorage!
init(syntaxParser:TRexSyntaxKitParser, textView:NSTextView) {
self.syntaxParser = syntaxParser
super.init()
if let textViewStorage = textView.textStorage {
self.textStorage = textViewStorage
self.textStorage.delegate = self
}
}
func textStorageDidProcessEditing(notification: NSNotification) {
let inputString = self.textStorage.string
let wholeRange = NSMakeRange(0, count(inputString))
self.textStorage.removeAttribute(NSForegroundColorAttributeName, range:wholeRange)
let attributes = self.syntaxParser!.parse(inputString)
print("Attributes: \(attributes)")
for attribDict: [String:AnyObject] in attributes {
let range = NSMakeRange(attribDict["rangeStart"] as! Int, attribDict["rangeLength"] as! Int)
self.textStorage.addAttribute(attribDict["attributeKey"] as! String, value:NSColor(hexString: attribDict["color"] as! String)!, range:range)
}
}
}
and this is how i call this class: 这就是我称之为这个课程的方式:
import Cocoa
class CodeEditorViewController: NSViewController {
@IBOutlet var codeTextView: NSTextView!
var syntaxParser:TRexSyntaxKitParser?
override func viewDidLoad() {
super.viewDidLoad()
self.syntaxParser = TRexSyntaxKitParser(language:"latex",theme:"classic")
let testClass = TestClass(syntaxParser: self.syntaxParser!, textView: self.codeTextView)
codeTextView.lnv_setUpLineNumberView()
}
but this produces the following error: 但是这会产生以下错误:
[NSFont textStorageDidProcessEditing:]: unrecognized selector sent to instance
I do not see where I would call the delegate method from NSFont ? 我没有看到从NSFont调用委托方法的位置? So to be precise: How can I refactor the first class into two different one ?
所以准确地说:我如何将第一类重构成两个不同的类?
Think about the memory management of this line: 想想这条线的内存管理:
let testClass = TestClass(syntaxParser: self.syntaxParser!, textView: self.codeTextView)
testClass
is a local variable . testClass
是一个局部变量 。 So what happens to your brand new TestClass instance? 那么你的全新TestClass实例会发生什么? It comes into existence and immediately vanishes in a puff of smoke when
viewDidLoad
comes to an end. 当
viewDidLoad
结束时,它就会出现并立即在一阵烟雾中消失 。
Thus, you now have a delegate pointing at an object that does not exist. 因此,您现在有一个委托指向不存在的对象。 Hence, the crash.
因此,崩溃。
Solution: make testClass
something that will persist long enough to do you some good - like, an instance property of your view controller. 解决方案:使
testClass
保持足够长的时间来为你做一些好事 - 比如视图控制器的实例属性。 That will give you exactly the refactoring you are after (this is a standard design pattern). 这将为您提供完全正在进行的重构(这是一种标准设计模式)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.