gpt4 book ai didi

ios - iOS-NSMutableArray是不可变的

转载 作者:行者123 更新时间:2023-12-01 17:53:40 27 4
gpt4 key购买 nike

我正在尝试在.h文件中声明并在.m文件中合成的NSMutable数组中编辑对象,但是该应用程序因调试错误而崩溃:Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'
使应用程序崩溃的行是:

[noteContent replaceObjectAtIndex:currentNote withObject:noteText.text];
noteContent在.h @property (nonatomic, strong) NSMutableArray* noteContent;中声明,在.m @synthesize noteContent中合成并在viewDidLoad中初始化
noteContent = [[NSMutableArray alloc] init];
noteContent = [standardUserDefaults objectForKey:@"noteContent"];

问题不在于替换nil对象,因为我检查了在该位置是否存储了实际的字符串。

感谢你的付出。

最佳答案

您已将NSArray分配给noteContent:

noteContent = [standardUserDefaults objectForKey:@"noteContent"];

因此,尽管您已将变量声明为可变数组,但所引用的实际对象是不可变的。试试这个:
noteContent = [[NSMutableArray alloc] initWithArray:[standardUserDefaults objectForKey:@"noteContent"]];

正如@Abizern在评论中所解释的那样,有一个要做的论点:
noteContent = [[standardUserDefaults objectForKey:@"noteContent"] mutableCopy];

但是,应该注意的是,采用这种方法,如果 noteContent返回 nil[standardUserDefaults objectForKey:@"noteContent"]将为 nil。因此,如果大概要向可变数组添加项目,则需要添加更多代码来处理 nil情况。

关于ios - iOS-NSMutableArray是不可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22284786/

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