如何复制 NSMutableAttributedString

问题描述 投票:0回答:1

我只是想知道如何复制

NSMutableAttributedString
。我有一个名为
text
的属性,我想在某个时刻保存其内容并在发生某些情况时恢复到它。我尝试创建一个名为
textCopy
的属性,我可以使用
@property (nonatomic, copy)
将其保存到其中,但是当我这样做时,出现运行时错误:

 -[NSConcreteAttributedString insertAttributedString:atIndex:]: unrecognized selector sent to instance.

我该如何实现这个目标?

更新了运行时错误。每当我将 NSMutableAttributedString 设置为

@property (nonatomic, copy)
时,我都会收到此消息。不明白为什么这不起作用,一般来说,无论我是否使用它的 setter 方法,复制参数似乎都不适用于 NSMutableAttributedString 。

iphone objective-c ios cocoa-touch core-text
1个回答
5
投票

问题是您已经使用

copy
属性声明了该属性,并且可能正在使用编译器生成的 setter。编译器生成的 setter 向对象发送
copy
消息以进行复制。
copy
消息会创建一个 immutable 副本。也就是说,它创建了一个
NSAttributedString
,而不是 一个 NSMutableAttributedString

解决此问题的一种方法是编写自己的使用

mutableCopy

 的 setter,如果您使用 ARC,则如下所示:

- (void)setTextCopy:(NSMutableAttributedString *)text { textCopy = [text mutableCopy]; }
如果您使用手动引用计数,则像这样:

- (void)setTextCopy:(NSMutableAttributedString *)text { // Careful copy/release dance in case text and textCopy // are the same object. id old = textCopy; textCopy = [text mutableCopy]; [old release]; }
另一个修复方法是使 

textCopy

 成为 
NSAttributedString
 而不是 
NSMutableAttributedString
,并使其余代码将其作为不可变对象使用。

© www.soinside.com 2019 - 2024. All rights reserved.