0

我显然没有得到什么。

我正在解析一个 XML 文档,所以我有一个 NSMutableString 可以附加到其中一个元素,因为 foundCharacters 被截断并分段执行。我可以让这一切正常工作,但我不明白为什么以某种方式这样做是行不通的。

@property (copy, nonatomic) NSMutableString *currentFoundCharacter;

这就是我为 ViewController 声明属性的方式。

然后我有:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
  {
    if (!currentFoundCharacter) {
      currentFoundCharacter = [[NSMutableString alloc] init]; // Have to do this or new strings never append to it.
    }
    if ([currentAttribute compare:@"description"] == NSOrderedSame && currentAttribute.length > 1) {
    [currentFoundCharacter appendString:[string copy]];
  }

现在这在这里有效。它将在一个元素中组合我想要的所有内容。但是如果我尝试使用合成方法,我会收到关于变异不可变对象的错误,所以基本上用 self.currentFoundCharacters 替换所有 currentFoundCharacters。

也许我误解了何时以及为什么使用属性与实例变量,但在 init 方法之外,因此我的印象是使用 setter / getter 更好。最后,我只想确保编写可维护的代码。

4

1 回答 1

3

在您的财产中使用保留而不是复制。Copy 给你一个不可变的副本。

于 2012-04-21T22:18:46.827 回答