butter_baby
butter_baby

Reputation: 888

NSMutableArray items are all exactly the same

I have a set of map annotations that I am iterating over to store into my own data model. I have checked with log statements to ensure that the coordinates are in fact different, which they are. However, when I attempt to iterate over that same array of pins and add the coordinate to my model all of the coordinates are exactly the same.

I know that my loop is the culprit, but can't quite figure out why that's happening:

NSMutableArray *modelArray = [NSMutableArray new];
    for (PinObject *currentPin in self.mapPins) {
        CLLocation *pinCoordinate = [[CLLocation alloc] initWithLatitude:currentPin.coordinate.latitude   longitude:currentPin.coordinate.longitude];

        AnnotationCameraModel *cameraModel = [self.cameraModel initWithData:pinCoordinate];
        coordinates[i] = currentPin.coordinate;
        [modelArray addObject:cameraModel];
    }

 for (AnnotationCameraModel *model in modelArray) {
        NSLog(@"Coordinate: %@", model.coordinate);
    }

When I log my points I end up with:

Coordinate: <+14.56841634,+121.03354250> +/- 0.00m (speed -1.00 mps / course -1.00) @ 11/17/16, 9:00:14 PM Philippine Standard Time
Coordinate: <+14.56841634,+121.03354250> +/- 0.00m (speed -1.00 mps / course -1.00) @ 11/17/16, 9:00:14 PM Philippine Standard Time
Coordinate: <+14.56841634,+121.03354250> +/- 0.00m (speed -1.00 mps / course -1.00) @ 11/17/16, 9:00:14 PM Philippine Standard Time

Any ideas?

Upvotes: 0

Views: 64

Answers (2)

Rok Jarc
Rok Jarc

Reputation: 18875

Unless self.cameraModel (property of the object holding this code) is some kind of factory object that produces AnnotationCameraModel objects with a method initWithData: your problem lies in line:

AnnotationCameraModel *cameraModel = [self.cameraModel initWithData:pinCoordinate];

I suspect this property is just a simple AnnotationCameraModel object and it's initializer (depends on how it's written) returns itself.

Change that line to:

AnnotationCameraModel *cameraModel = [[AnnotationCameraModel alloc] initWithData:pinCoordinate];

Line coordinates[i] = currentPin.coordinate; also doesn't make much sense. You probably want something in the lines of coordinates[i++] = currentPin.coordinate;

Upvotes: 3

riyaz
riyaz

Reputation: 1103

There should be a two part creation

1 -  alloc 
2 -  init

You are basically initialising an already initialised object.

In every init method there would be a check

if (self == nil)
{
self = [super init];
}
return self;

so basically

[self.cameraModel initWithData:pinCoordinate]

does nothing but returning self because it is not nil.

Do this

 AnnotationCameraModel *cameraModel = [[AnnotationCameraModel alloc]initWithData:pinCoordinate];

Upvotes: 3

Related Questions