NSArray 与 NSMutableArray

发布于 2025-01-07 00:42:14 字数 681 浏览 4 评论 0原文

我有一个包含两个实体的核心数据堆栈:“客户端”和“汽车”。这是一种一对多的关系。我有两个 tableViewControllers 首先显示客户端,然后一旦选择了客户端,就会显示该客户端汽车的列表。

我目前在我的第二个 tableViewController viewDidLoad 方法中使用以下代码片段...

NSSet *cars = client.cars;
carsArray = [cars allObjects];

carsArray 是一个 NSArray 并在第二个中声明和合成表视图控制器。如果我尝试将 carsArray 设为 NSMutableArray (这样我可以在汽车被删除时对其进行编辑),我会收到以下编译器警告...

不兼容当从不同的 Objective-C 类型传递“setCarsArray:”的参数 1 时,Objective-C 类型为“struct NSArray *”,预期为“struct NSMutableArray *”

有人可以向我解释为什么这适用于 NSArray< /代码> 但不是一个 NSMutableArray 好吗?

非常感谢

I have a core data stack with 2 entities: 'Client' and 'Car'. It is a one to may relationship. I have two tableViewControllers to display firstly the clients, and then once a client has been chosen a list of that clients cars.

I am currently using the following code fragment in my second tableViewController viewDidLoad method...

NSSet *cars = client.cars;
carsArray = [cars allObjects];

carsArray is a NSArray and is declared and synthesized in the second tableViewCotroller. If I try and make carsArray an NSMutableArray (so I can edit it later in the event a car is deleted) I get the following compiler warning...

Incompatible Objective-C types 'struct NSArray *', expected 'struct NSMutableArray *' when passing argument 1 of 'setCarsArray:' from distinct Objective-C type

Could someone explain to me why this works with a NSArray but not an NSMutableArray please?

Many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞳孔里扚悲伤 2025-01-14 00:42:14

allObjects 方法返回 NSArray *,如果您只是尝试将其分配给 NSMutableArray 属性,则不会转换对象本身。

您需要使用 +[NSMutableArray arrayWithArray:] 或更通用的方法 -[NSObject mutableCopy]

[self setCarsArray:[[cars allObjects] mutableCopy]];

对于 Objective-C 中的所有可变类都是这种情况:从不可变对象创建可变对象,您必须显式调用转换方法。

allObjects method returns NSArray * and if you simply try to assign it to an NSMutableArray property you are not converting the object itself.

You need to use +[NSMutableArray arrayWithArray:] or a more generic method -[NSObject mutableCopy]:

[self setCarsArray:[[cars allObjects] mutableCopy]];

This will be the case for all mutable classes in Objective-C: to create a mutable object from immutable you'll have to explicitly call the conversion methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文