1

I have the following piece of code in which I have inherited a class from NSMutableAttributedString and when I call the append method within the method of my class, app crashes. I just want to learn the reason. Can anyone help me?

 class Str: NSMutableAttributedString {

 override init() {
    super.init()
 }

 required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
 }

 func getStr(s:String) {
    self.append(NSMutableAttributedString.init(string: s))
    print(self)
 }

}

The error message is:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -string only defined for abstract class. Define -[string.str string]!'

Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43
Usama Azam
  • 403
  • 5
  • 13
  • 1
    It's always helpful to include the error message you get when the app crashes. – James P Dec 07 '18 at 11:20
  • Hi Usama, As James already said, try to include as much information as possible like the error you get. For more information on how to get the best results by asking 'good' questions check https://stackoverflow.com/help/how-to-ask – ophychius Dec 07 '18 at 11:25
  • error message in console is this: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -string only defined for abstract class. Define -[string.str string]!' – Usama Azam Dec 07 '18 at 11:27
  • `NSMutableAttributedString` is a class cluster, so cannot be subclassed. https://stackoverflow.com/questions/8360992/unrecognized-selector-error-when-calling-a-supers-initwithattributedstring-met – James P Dec 07 '18 at 11:48
  • Thanks @JamesP for this information. – Usama Azam Dec 07 '18 at 12:11
  • Can't you use extension instead? Because as stated in the link provided by @JamesP, it's not recommended to subclass it (I recall that there was a warning before in the doc but not anymore, memory is tricking me?). There are plenty of methods to override to make it work. – Larme Dec 08 '18 at 11:31
  • yes @Larme your point looks valid, thanks for recommendation. – Usama Azam Dec 10 '18 at 05:05

1 Answers1

0

try this code to append string in attributed string, i hope it helps you.

func getStr(_ newstr:String, attrib:[NSAttributedString.Key: Any]) {
    let newText = NSMutableAttributedString(string: newstr, attributes: attrib)
    self.append(newText)
    print(self)
 }

you should pass newstr and attrib like below.

let newstr: newstr = "your text here"
let attrib: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 15)]
AtulParmar
  • 4,358
  • 1
  • 24
  • 45