Convert NSMutableAttributedString to NSString
Asked Answered
G

4

39

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?

Gilt answered 11/10, 2013 at 3:44 Comment(0)
A
86

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
Afternoons answered 11/10, 2013 at 3:45 Comment(1)
Yeah I just realized the label has attributedText property as well. Thanks for the reply though!! :)Gilt
J
26

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

So:

NSAttributtedString* someString;
NSString* string = someString.string;
Jingo answered 14/4, 2016 at 16:43 Comment(2)
You saved me buddy. sorry stackoverflow does not allow me to upvote this more than one.Sard
I agree. I wish I could upvote more than once. This greatly simplified my code.Martguerita
M
0

NSAttributtedString have a property string and it is read only property you can not change it.

NSAttributtedString* attributtedString;
NSString* plainString = attributtedString.string;
Mejia answered 20/2, 2020 at 12:59 Comment(0)
Y
-1

Apart from @rmaddy's answer, mine case is different here.

Actually I used NSMutableAttributedString in JSON parsing to send details on server.

At parsing time I got exception because NSMutableAttributedString contains information about other attributes too, like color space. Because of that it wont parse.

I tried many other ways but finally got solution to get string using below code:

// "amountString" is NSMutableAttributedString string object

NSMutableAttributedString *mutableString = (NSMutableAttributedString *)amountString;
amountValueString = [mutableString string];
amountValueString = [NSString stringWithFormat:@"%@", amountString];

NSRange fullRange = NSMakeRange(0, amountString.length);
NSAttributedString *attStr = [mutableString attributedSubstringFromRange:fullRange];
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute:NSPlainTextDocumentType};

NSData *textData = [attStr dataFromRange:fullRange documentAttributes:documentAttributes error:NULL];
NSString *amountValueString = [[NSString alloc] initWithData:textData encoding:NSUTF8StringEncoding];
Yingling answered 25/3, 2016 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.