ios - 添加到数组后,我的模型中的属性将针对每个项目进行复制

标签 ios objective-c

我正在创建一个模型,然后将该模型添加到一个数组中。但是,一旦我添加了多个项目,我的模型中的一些属性就被复制了。我有以下 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/

相关文章:

iphone - 在 Split View Controller 中选择主视图选项卡上的更改详细 View

ios - 连续语音识别1分钟后无需重启

iphone - 我们可以在 XCode 4.0 中放大/缩小 Xib 文件 View 吗?

objective-c - 如何在 Objective-C 中对 init 方法进行单元测试?

iphone - UICollectionView didselect 不起作用

ios - localised.string 在设置中不可用的语言

ios - NSThread 用于并发操作

iphone - 动画 UITextView 时打字

objective-c - Objective-C 中的 AES 字符串加密

ios - 通过桥接 header 导入到 Swift 项目的 Objective C 库只能在 AppDelegate 中看到,而在其他类中看不到