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?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
tech_human
  • 6,592
  • 16
  • 65
  • 107

4 Answers4

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
Devbot10
  • 1,193
  • 18
  • 33
rmaddy
  • 314,917
  • 42
  • 532
  • 579
25

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

So:

NSAttributtedString* someString;
NSString* string = someString.string;
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Juraj Antas
  • 3,059
  • 27
  • 37
0

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

NSAttributtedString* attributtedString;
NSString* plainString = attributtedString.string;
Mohammad Parvez
  • 409
  • 4
  • 12
-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];
Kampai
  • 22,848
  • 21
  • 95
  • 95