[英]How to copy a NSMutableAttributedString
I'm just wondering how I can make a copy of an NSMutableAttributedString
. 我只是想知道如何制作NSMutableAttributedString
的副本。 I have a property called text
that I'd like to save its contents at a certain point and revert back to it in case something happens. 我有一个名为text
的属性,我想在某个点保存其内容,并在发生某些情况时还原为该属性。 I've tried making a property called textCopy
where I can save it to with @property (nonatomic, copy)
but I get a runtime error when I do this: 我尝试制作一个名为textCopy
的属性,可以在其中使用@property (nonatomic, copy)
将其保存到该@property (nonatomic, copy)
但是这样做时会出现运行时错误:
-[NSConcreteAttributedString insertAttributedString:atIndex:]: unrecognized selector sent to instance.
How would I accomplish this? 我将如何完成?
Updated with run time error. 更新时出现运行时错误。 I'm getting this anytime I set the NSMutableAttributedString to @property (nonatomic, copy)
. 每当我将NSMutableAttributedString设置为@property (nonatomic, copy)
得到此消息。 Not understanding why this wouldn't work, in general the copy paramter doesn't seem to work with NSMutableAttributedString whether I'm using its setter method or not. 不理解为什么这不起作用,通常无论我是否使用其setter方法,复制参数似乎都不能与NSMutableAttributedString一起使用。
The problem is that you've declared the property with the copy
attribute, and are presumably using the compiler-generated setter. 问题是您已经使用copy
属性声明了该属性,并且大概使用了编译器生成的setter。 The compiler-generated setter sends the copy
message to the object to make a copy. 编译器生成的设置器将copy
消息发送到对象以进行复制。 The copy
message makes an immutable copy. copy
消息将生成不可变的副本。 That is, it creates an NSAttributedString
, not an NSMutableAttributedString
. 也就是说,它创建一个NSAttributedString
, 而不是 NSMutableAttributedString
。
One way to fix this is to write your own setter that uses mutableCopy
, like this if you're using ARC: 解决此问题的一种方法是编写自己的使用mutableCopy
的setter,如果使用的是ARC,则如下所示:
- (void)setTextCopy:(NSMutableAttributedString *)text {
textCopy = [text mutableCopy];
}
or like this if you're using manual reference counting: 如果您使用人工参考计数,则可以这样:
- (void)setTextCopy:(NSMutableAttributedString *)text {
[textCopy release];
textCopy = [text mutableCopy];
}
Another fix would be to make textCopy
be an NSAttributedString
instead of an NSMutableAttributedString
, and make the rest of your code work with it as an immutable object. 另一种解决将是使textCopy
是NSAttributedString
而不是NSMutableAttributedString
,并与它的代码工作的其余部分为不可变对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.