Reputation: 7100
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?
Upvotes: 39
Views: 49046
Reputation: 318794
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
Upvotes: 86
Reputation: 417
NSAttributtedString have a property string and it is read only property you can not change it.
NSAttributtedString* attributtedString;
NSString* plainString = attributtedString.string;
Upvotes: 0
Reputation: 2712
NSAttributtedString
includes a .string
property. From there, you can take NSString
without attributes.
So:
NSAttributtedString* someString;
NSString* string = someString.string;
Upvotes: 26
Reputation: 23053
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];
Upvotes: -1