gpt4 book ai didi

objective-c - 为什么我得到 "Attempt to mutate immutable object with replaceOccurrencesOfString:"当所有变量都是可变的

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:18:02 26 4
gpt4 key购买 nike

非常简单的代码,我可以说它在 Xcode 4.1 中按预期工作,但在 Xcode 4.2 中中断。这是有问题的代码:

-(void)mergeDevData2Email:(NSMutableString *)target codeArray:(NSArray *)array1 valueArray:(NSArray *)array2 {
NSUInteger n = 0;

for (NSMutableString *aCode in array1) {
if ([array2 count] > n) {
NSMutableString *arg = [array2 objectAtIndex:(NSUInteger)n];

NSLog(@"Target isKindOf NSMutableString: %@", ([target isKindOfClass:[NSMutableString class]]) ? @"YES" :@"NO");
NSLog(@"aCode isKindOf NSMutableString: %@", ([aCode isKindOfClass:[NSMutableString class]]) ? @"YES" :@"NO");
NSLog(@"arg isKindOf NSMutableString: %@", ([arg isKindOfClass:[NSMutableString class]]) ? @"YES" :@"NO");

[target replaceOccurrencesOfString:aCode withString:arg options:NSLiteralSearch range:NSMakeRange(0, [target length])];
n++;
}
else {
break;
}
}
}

这是 NSLogs 显示的内容:

2011-11-03 15:42:59.967 TestProg[30413:c503] 目标 isKindOf NSMutableString: 是

2011-11-03 15:42:59.968 TestProg[30413:c503] aCode isKindOf NSMutableString: YES

2011-11-03 15:42:59.969 TestProg[30413:c503] arg isKindOf NSMutableString: 是

当我执行 [target replaceOcurances... 代码行时我崩溃了-

程序收到信号:“SIGABRT”。

在控制台日志中有以下内容-

2011-11-03 15:43:26.828 TestProg[30413:c503] * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试使用 replaceOccurrencesOfString:withString 改变不可变对象(immutable对象):选项:范围:'

我的问题是,我要在哪里尝试改变不可变对象(immutable对象)?其次,为什么这在 Xcode 4.1 中执行得很好?当然,对于 Xcode 4.1,所有播放器看起来都是可变的。 Xcode 4.2 有什么不同 ?我在这里遗漏了一些微妙的东西。

最佳答案

我怀疑某些字符串并不是真正可变的字符串(可能是“target”,因为这是您要修改的字符串)。这也让我困惑了一段时间,但是“isKindOf:”不区分可变字符串和非可变字符串。我相信即使字符串不可变,您的 NSLog 查询也会返回 YES。

如果您在调试器中停止,您应该能够检查对象并确定它们是否真的是可变的(“真实的”类名应该与对象一起显示)。

至于为什么这在 4.1 而不是 4.2 中起作用,很难说。可能是某些返回 NSString 的系统例程用于返回 NSMutableString 但不再返回。

如果我是正确的,您将需要向上移动堆栈以找出目标来自何处。在某些时候,它可能已经从 NSString 转换为 NSMutableString。

关于objective-c - 为什么我得到 "Attempt to mutate immutable object with replaceOccurrencesOfString:"当所有变量都是可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com