gpt4 book ai didi

objective-c "mutating method sent to immutable object"错误

转载 作者:太空狗 更新时间:2023-10-30 03:34:14 24 4
gpt4 key购买 nike

我是 objective-c 的新手,尝试为 iphone 创建一个小应用程序。
除了这里的这个小错误,我几乎完成了。实际上,我已经用谷歌搜索了几个小时来找到合适的解决方案,但遗憾的是我找不到有效的解决方案。
我在这里使用本教程来构建一个 UITableView:UITableView Tutorial完整的错误消息如下所示:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '* -[NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

这是数据 Controller header :MyLinksDataController.h

@interface MyLinksDataController : NSObject {

NSMutableArray *tableList; //<---important part

}

- (unsigned)countOfList;
- (id)objectInListAtIndex:(unsigned)theIndex;
- (void)addData:(NSString *)data; //<---important part
- (void)removeDataAtIndex:(unsigned)theIndex;

@property (nonatomic, copy, readwrite) NSMutableArray *tableList; //<---important part

.....

以及数据 Controller 方法:MyLinksDataController.m

#import "MyLinksDataController.h"

@implementation MyLinksDataController

@synthesize tableList;

- (id)init {

if (self = [super init]) {

NSLog(@"Initilizing DataController");
//Instantiate list
NSMutableArray *localList = [[NSMutableArray alloc] init];
self.tableList = [localList copy];
[localList release];

//Add initial Data
[self addData:@"AAAAAAAAAAAAAA"];
[self addData:@"BBBBBBBBBBBBBB"];

}

return self;

}

-----------------------------稍后在源代码中------------ ------------------------

- (void)addData:(NSString*)data; {

[tableList addObject:data]; //<---- here the app crashes

}

如果有任何帮助,我将不胜感激。

提前感谢您的支持。

丹尼尔

最佳答案

copy 消息发送到 NSMutableArray —— 如以下 init 中的语句 —— 返回一个不可变的副本。

self.tableList = [localList copy];

Cocoa 文档使用不可变 一词来指代只读的、初始化后不能更改的对象。因此,对 addObject: 的后续调用将失败并显示一条错误消息。

请注意上面的赋值语句不会触发任何编译器警告。 copy 返回一个 id,就编译器而言,它很适合 NSMutableArray* tableList。这里也没有运行时错误,因为没有消息传递; NSArray 指针只是放在 NSMutableArray 指针变量中。

要获取可变副本,请改用 mutableCopy

请注意,copymutableCopy 都会创建一个新数组并将原始数组的内容复制到其中。副本中的更改不会反射(reflect)在原件中。如果您只需要对原始数组的另一个引用,请改用 retain

您可以在 copyWithZone reference 的讨论部分找到更多详细信息在NSMutableCopying protocol reference .

关于 objective-c "mutating method sent to immutable object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1224040/

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