2013-10-11 89 views
26

我們不能將NSMutableAttributedString轉換爲NSString將NSMutableAttributedString轉換爲NSString

我有兩個NSMutableAttributedStrings,我追加了第二根弦到1如下:

[string1 appendAttributedString:string2];

因爲我必須在標籤上顯示字符串1我做的:

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

我得到"unrecognized selector sent to instance"錯誤。

我在這裏做錯了什麼嗎?這不是將NSMutableAttributedString分配給標籤文本屬性的正確方法嗎?

回答

67

您不能使用強制轉換將對象從一種類型轉換爲另一種類型。使用提供的方法:

self.label1.text = [string1 string]; 

更重要的是,使用屬性串:

self.label1.attributedText = string1; 
+0

是啊,我才意識到標籤已attributedText財產爲好。感謝您的回覆!! :) –

0

除了@ rmaddy的回答,我的情況是不同的這裏。

其實我在JSON解析中用NSMutableAttributedString來發送服務器上的細節。

在解析時,我得到了異常,因爲NSMutableAttributedString也包含有關其他屬性的信息,例如color space。因爲它不會解析。

我試過很多其他方法,但最後得到的解決方案使用下面的代碼來獲得字符串:

// "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]; 
10

NSAttributtedString包括.string屬性。從那裏,你可以採取NSString沒有屬性。

所以:

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

你救了我哥們。對不起,stackoverflow不允許我使用這個不止一個。 – iNasir