Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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

So:

NSAttributtedString* someString;
NSString* string = someString.string;

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

NSAttributtedString* attributtedString;
NSString* plainString = attributtedString.string;

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];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top