我正在创建一个模型,然后将该模型添加到一个数组中。但是,一旦我添加了多个项目,我的模型中的一些属性就被复制了。我有以下 DrawnLayerModel 类型的属性:
model.overlay
model.fillcolor
model.linecolor
model.overlayString
OverlayString 是我目前最关心的属性。这是我创建模型对象并将其添加到我的数组的地方:
-(void)saveOverlay {
DrawnLayerModel *model = [self.drawnLayerModel initWithOverlay:self.mapView.overlays.lastObject fillColor:self.customFillColor lineColor:self.customLineColor overlayTitle:self.layerName];
[self.overlaysArray addObject:model];
for (DrawnLayerModel *model in self.overlaysArray) {
NSLog(@"Model ====> %@.", model);
NSLog(@"Title ====> %@.", model.overlayTitle);
}
}
每次按下此按钮时,它都会添加一个新的模型对象:
- (IBAction)saveButtonPressed:(id)sender {
UITextField *textfield = alertController.textFields.firstObject;
self.layerName = textfield.text;
[self.helpers createSuccessAlertContoller:self mapView:self.mapView title:@"Layer Successfully Saved!" message:@"Choose the layers button in the navigation bar to access saved layers."];
[self saveOverlay];
}
我得到以下输出:
2018-02-05 13:47:12.387032-0800 prism[4910:1739598] Model ====> <DrawnLayerModel: 0x1c424d2c0>
2018-02-05 13:47:12.387166-0800 prism[4910:1739598] Title ====> Blue.
2018-02-05 13:47:12.387204-0800 prism[4910:1739598] Model ====> <DrawnLayerModel: 0x1c424d2c0>
2018-02-05 13:47:12.387235-0800 prism[4910:1739598] Title ====> Blue.
现在,如果您查看 DrawnLayerModel 输出,这些数字令人怀疑地相同:
0x1c424d2c0
那是保存对象的地址吗?为什么我的属性被复制?
最佳答案
Once I add multiple models to my array
问题在于执行此操作的代码:
DrawnLayerModel *model = [self.drawnLayerModel initWithOverlay:self.mapView.overlays.lastObject fillColor:self.customFillColor lineColor:self.customLineColor overlayTitle:self.layerName];
[self.overlaysArray addObject:model];
您只是一遍又一遍地重新初始化同一个持久对象 (self.drawnLayerModel
)。因此,您将相同 对象添加到数组两次(或更多次)。将对象添加到数组并不会复制它,对象指针只是一个引用,因此您可以将对一个对象的多个引用添加到数组。
这里的真正的问题是您违反了 Objective-C 中最基本的实例化法则:永远不要在没有说 alloc 的情况下说
在同一组方括号中。反之亦然:永远不要在同一行中不说 init
init
就说 alloc
。
关于ios - 添加到数组后,我的模型中的属性将针对每个项目进行复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48632108/