简体   繁体   English

将 NSMutableAttributedString 转换为 NSString

[英]Convert NSMutableAttributedString to NSString

Can we not convert NSMutableAttributedString to NSString ?我们不能将NSMutableAttributedString转换为NSString吗?

I have two NSMutableAttributedStrings and I am appending the 2nd string onto 1st as below:我有两个NSMutableAttributedStrings ,我将第二个字符串附加到第一个字符串,如下所示:

[string1 appendAttributedString:string2];

Since I have to display string1 on a label I do:因为我必须在标签上显示 string1,所以我这样做:

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

I am getting "unrecognized selector sent to instance" error.我收到"unrecognized selector sent to instance"错误。

Am I doing anything wrong here?我在这里做错了什么吗? Isn't this the correct way to assign a NSMutableAttributedString to text property of a label?这不是将NSMutableAttributedString分配给标签的 text 属性的正确方法吗?

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

NSAttributtedString includes a .string property. NSAttributtedString包含一个.string属性。 From there, you can take NSString without attributes.从那里,您可以使用没有属性的NSString

So:所以:

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

NSAttributtedString have a property string and it is read only property you can not change it. NSAttributtedString 有一个属性字符串,它是只读属性,您不能更改它。

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

Apart from @rmaddy's answer, mine case is different here.除了@rmaddy 的回答,我的情况在这里有所不同。

Actually I used NSMutableAttributedString in JSON parsing to send details on server.实际上,我在 JSON 解析中使用了NSMutableAttributedString来在服务器上发送详细信息。

At parsing time I got exception because NSMutableAttributedString contains information about other attributes too, like color space .在解析时,我遇到了异常,因为NSMutableAttributedString包含有关其他属性的信息,例如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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM