NSArray 与 NSMutableArray
我有一个包含两个实体的核心数据堆栈:“客户端”和“汽车”。这是一种一对多的关系。我有两个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
allObjects
方法返回NSArray *
,如果您只是尝试将其分配给NSMutableArray
属性,则不会转换对象本身。您需要使用
+[NSMutableArray arrayWithArray:]
或更通用的方法-[NSObject mutableCopy]
:对于 Objective-C 中的所有可变类都是这种情况:从不可变对象创建可变对象,您必须显式调用转换方法。
allObjects
method returnsNSArray *
and if you simply try to assign it to anNSMutableArray
property you are not converting the object itself.You need to use
+[NSMutableArray arrayWithArray:]
or a more generic method-[NSObject 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.