Domanda

In my mapview, the user can make his own map pin by tapping on the screen. He can set multiple pins. However, my code for saving only saves the last pin he has made and not the previous ones. How do I make it save the previous ones as well?

- (void)addPinToMap:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
        return;

    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
    CLLocationCoordinate2D touchMapCoordinate =
    [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];

     NSMutableArray *pincoords = [[NSMutableArray alloc] init];



    CLLocationCoordinate2D coordinate = { touchMapCoordinate.latitude, touchMapCoordinate.longitude };
[pincoords addObject:[NSValue valueWithBytes:&coordinate objCType:@encode(CLLocationCoordinate2D)]];


    MapAnnotation *toAdd = [[MapAnnotation alloc]init];

    toAdd.coordinate = touchMapCoordinate;
    toAdd.title = @"Svampe Spot";

    [self.mapView addAnnotation:toAdd];

    //Save pin section..

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:pincoords forKey:@"saveCoords"];
[userDefaults synchronize];
}

EDIT: So i made some changes. I made an NSMutable array and added the coordinates to it. However, the app terminates when trying to make a pin due to this: [NSUserDefaults setObject:forKey:]: attempt to insert non-property list object.

Everytime i try to add coordinates to mutable array i seem to get that message, what am i doing wrong?

È stato utile?

Soluzione

Every time you write a new pin to the user defaults, it overwrites the old one. Instead, write an NSArray or NSMutableArray to the user defaults and add/remove pins from it.

UPDATE: First of all, the NSMutableArray needs to be copied from the user defaults, not alloc/inited. This way, the array will already contain the previously saved points in it:

NSMutableArray *pincoords = (NSMutableArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"saveCoords"];

This will return a mutable array with your previously saved coordinates.

As for the method you are using to store the coordinate in the array, I think you have the right idea, but I've personally never done it that way. NSArrays can only store objects, and CLLocationCoordinate2D is not an object (probably a C struct like NSRect, I've never used it before). It needs to be converted to a NSCoding compliant object, such as NSString, NSNumber, or NSDictionary. What you could do is create a function to manually enter the coordinate values (wrapped in an NSNumber) into a NSDictionary (using keys such as @"Lat" and @"Long" for your coordinates), and then store the NSDictionary in your mutable array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top