Store CLLocationCoordinate2D to NSUserDefaults

2020-02-10 06:02发布

问题:

I am new to iphone development, and i want to store CLLocationCoordinate2D object to NSUserDefaults. I am Trying

    [defaults setObject:location forKey:@"userLocation"];

But it gives error 'Sending CLLocationCoordinate2D to parameter of incompatible type id'

So How to store CLLocationCoordinate2D into NSUserDefaults? Thanks.

回答1:

As pdrcabrod said,

"A default object must be a property list, that is, an instance of NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary."

I use this to store,

    NSNumber *lat = [NSNumber numberWithDouble:location.latitude];
    NSNumber *lon = [NSNumber numberWithDouble:location.longitude];
    NSDictionary *userLocation=@{@"lat":lat,@"long":lon};

    [[NSUserDefaults standardUserDefaults] setObject:userLocation forKey:@"userLocation"];
    [[NSUserDefaults standardUserDefaults] synchronize];

And access using,

    NSDictionary *userLoc=[[NSUserDefaults standardUserDefaults] objectForKey:@"userLocation"];
    NSLog(@"lat %@",[userLoc objectForKey:@"lat"]);
    NSLog(@"long %@",[userLoc objectForKey:@"long"]);


回答2:

This is what i would do:

NSData *data = [NSData dataWithBytes:&coordinate length:sizeof(coordinate)];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"key"];
[[NSUserDefaults standardUserDefaults] synchronize];

Then you can retrieve it like this:

NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"key"];
CLLocationCoordinate2D coordinate;
[data getBytes:&coordinate length:sizeof(coordinate)];


回答3:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData

See: NSUserDefaults



回答4:

You can set like this..

CLLocationCoordinate2D coordinate; // need to set your coordinate here

[[defaults setObject:[NSString stringWithFormat:@"%g",coordinate.latitude] forKey:@"latitude"] ];
[[defaults setObject:[NSString stringWithFormat:@"%g",coordinate.longitude] forKey:@"longitude"] ];

i Hope it helps.



回答5:

As others have said, first convert it into a Dictionary or Data object and then save it as you normally would. In Swift I highly recommend using extensions. Here's what I did:

extension CLLocationCoordinate2D {

    private static let Lat = "lat"
    private static let Lon = "lon"

    typealias CLLocationDictionary = [String: CLLocationDegrees]

    var asDictionary: CLLocationDictionary {
        return [CLLocationCoordinate2D.Lat: self.latitude,
                CLLocationCoordinate2D.Lon: self.longitude]
    }

    init(dict: CLLocationDictionary) {
        self.init(latitude: dict[CLLocationCoordinate2D.Lat]!,
                  longitude: dict[CLLocationCoordinate2D.Lon]!)
    }

}


回答6:

import CoreLocation

// Store an array of CLLocationCoordinate2D
func storeCoordinates(_ coordinates: [CLLocationCoordinate2D]) {
let locations = coordinates.map { coordinate -> CLLocation in
    return CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
let archived = NSKeyedArchiver.archivedData(withRootObject: locations)
UserDefaults.standard.set(archived, forKey: "coordinates")
UserDefaults.standard.synchronize()
}

// Return an array of CLLocationCoordinate2D
func loadCoordinates() -> [CLLocationCoordinate2D]? {
guard let archived = UserDefaults.standard.object(forKey: "coordinates") as? Data,
    let locations = NSKeyedUnarchiver.unarchiveObject(with: archived) as? [CLLocation] else {
        return nil
}

let coordinates = locations.map { location -> CLLocationCoordinate2D in
    return location.coordinate
}
        return coordinates
}

Now Let's test the implementation:

let testCoordinates = [
CLLocationCoordinate2D(latitude: 0.123456789, longitude: 0.123456789),
CLLocationCoordinate2D(latitude: 1.123456789, longitude: 1.123456789),
CLLocationCoordinate2D(latitude: 2.123456789, longitude: 2.123456789)
]

self.storeCoordinates(testCoordinates)

let coordinates = loadCoordinates()
print(coordinates)