butter_baby
butter_baby

Reputation: 888

Properties in my model are being duplicated for each item after adding to an array

I am creating a model and then adding that model to an array. However, once I add more than one item, some of the properties in my model ended up being duplicated.I have the following properties of type DrawnLayerModel:

model.overlay
model.fillcolor
model.linecolor
model.overlayString

OverlayString is the property that I'm most concerned with at the moment. Here is where I create the model object and add it to my array:

-(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);
    }
}

Every time this button is pushed it adds a new model object:

- (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];
}

I get the following output:

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.

Now if you look at the DrawnLayerModel output these numbers are suspiciously the same:

0x1c424d2c0

Is that an address where the object was saved? Why are my properties being duplicated?

Upvotes: 0

Views: 45

Answers (1)

matt
matt

Reputation: 535511

Once I add multiple models to my array

The problem is with the code that does that:

DrawnLayerModel *model = [self.drawnLayerModel initWithOverlay:self.mapView.overlays.lastObject fillColor:self.customFillColor lineColor:self.customLineColor overlayTitle:self.layerName];
[self.overlaysArray addObject:model];

You are just reinitializing the same persistent object over and over (self.drawnLayerModel). Thus, you are adding the same object to the array twice (or more). Adding an object to an array doesn't copy it, and an object pointer is merely a reference, so you are able to add multiple references to one object to an array.

The real problem here is that you have broken the most basic law of instantiation in Objective-C: Never say init without having said alloc in the very same set of square brackets. And vice versa: never say alloc without saying init in the same line.

Upvotes: 2

Related Questions