ios - Swift Delegate in own class -
i trying write first swift mac application. have hard times refactoring code 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)") 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 how call 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 produces following error:
[nsfont textstoragedidprocessediting:]: unrecognized selector sent instance
i not see call delegate method nsfont ? so precise: how can refactor first class 2 different 1 ?
think memory management of line:
let testclass = testclass(syntaxparser: self.syntaxparser!, textview: self.codetextview)
testclass
local variable. happens brand new testclass instance? comes existence and vanishes in puff of smoke when viewdidload
comes end.
thus, have delegate pointing @ object not exist. hence, crash.
solution: make testclass
persist long enough - like, instance property of view controller. give refactoring after (this standard design pattern).
Comments
Post a Comment