Convert NSMutableAttributedString to NSString

45,225

Solution 1

You can't use a cast to convert an object from one type to another. Use the provided method:

label1.text = [string1 string];

Better yet, use the attributed string:

label1.attributedText = string1

Solution 2

NSAttributtedString includes a .string property. From there, you can take NSString without attributes.

So:

NSAttributtedString* someString;
NSString* string = someString.string;
Share:
45,225
tech_human
Author by

tech_human

Updated on March 24, 2020

Comments

  • tech_human
    tech_human about 4 years

    Can we not convert NSMutableAttributedString to NSString?

    I have two NSMutableAttributedStrings and I am appending the 2nd string onto 1st as below:

    [string1 appendAttributedString:string2];

    Since I have to display string1 on a label I do:

    self.label1.text = (NSString *)string1;
    

    I am getting "unrecognized selector sent to instance" error.

    Am I doing anything wrong here? Isn't this the correct way to assign a NSMutableAttributedString to text property of a label?

  • tech_human
    tech_human over 10 years
    Yeah I just realized the label has attributedText property as well. Thanks for the reply though!! :)
  • Nasir
    Nasir over 7 years
    You saved me buddy. sorry stackoverflow does not allow me to upvote this more than one.
  • Lewis Edward Garrett
    Lewis Edward Garrett over 2 years
    I agree. I wish I could upvote more than once. This greatly simplified my code.