Sam*_*Sam 1 iphone objective-c nsmutablearray ios
我正在尝试编辑在.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];
Run Code Online (Sandbox Code Playgroud)
noteContent在.h中声明@property (nonatomic, strong) NSMutableArray* noteContent;,在.m中合成@synthesize noteContent并在viewDidLoad中初始化
noteContent = [[NSMutableArray alloc] init];
noteContent = [standardUserDefaults objectForKey:@"noteContent"];
Run Code Online (Sandbox Code Playgroud)
问题不在于替换nil对象,因为我检查了该位置,存储了一个实际的字符串.
感谢你的付出.
您已分配NSArray到noteContent:
noteContent = [standardUserDefaults objectForKey:@"noteContent"];
Run Code Online (Sandbox Code Playgroud)
因此,虽然您已将变量声明为可变数组,但引用的实际对象是不可变的.试试这个:
noteContent = [[NSMutableArray alloc] initWithArray:[standardUserDefaults objectForKey:@"noteContent"]];
Run Code Online (Sandbox Code Playgroud)
正如@Abizern在评论中解释的那样,有一个争论要做:
noteContent = [[standardUserDefaults objectForKey:@"noteContent"] mutableCopy];
Run Code Online (Sandbox Code Playgroud)
然而,应该指出的是,用这种方法,noteContent将是nil,如果[standardUserDefaults objectForKey:@"noteContent"]回报nil.因此,如果您想要将项添加到可变数组中,则需要添加更多代码来处理该nil情况.
| 归档时间: |
|
| 查看次数: |
352 次 |
| 最近记录: |