I have an array of CLLocation
data that I would like to archive. Should the NSUserDefaults
system be used? Otherwise, how best to archive the CLLocation
data?
To correctly store a CLLocation without loss of information, use an NSKeyedArchiver like this:
CLLocation *myLocationToStore = ...; // (a CLLocation object)
NSData *locationData = [NSKeyedArchiver archivedDataWithRootObject:myLocationToStore];
This can then be archived to NSUserDefaults, and likewise decoded just as simply when you retrieve it with NSKeyedUnarchiver:
CLLocation *myStoredLocation = (CLLocation *)[NSKeyedUnarchiver unarchiveObjectWithData:locationData];
The Swift equivalent functions are:
class func archivedDataWithRootObject(_ rootObject: AnyObject) -> NSData]
class func unarchiveObjectWithData(_ data: NSData) -> AnyObject?
UserDefaults can only store certain types of data, and should be used to store user preference information, not arbitrary application state data.
To quote the Apple docs:
The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved.
More info here.
If your CLLocation data really does count as user preference info (which I'm not convinced of), you'll have to map the info inside CLLocation onto types that are compatible with NSUserDefaults. Read the docs for NSUserDefaults.
If your CLLocation data isn't user preference info, but just application data/state that you need to preserve, you have a few options; you could store it in core data, or you could use keyed archiving - see this tutorial, for example.
Found out the solution using nsarchiver as you said it worked like charm thanks. Here is what i did.
- (id)initWithCoder:(NSCoder *)aDecoder
{
self.PlaceName=[aDecoder decodeObjectForKey:@"inapPlaceName"];
float lat, long1;
lat=[aDecoder decodeDoubleForKey:@"inapCoordinateLat"];
long1=[aDecoder decodeDoubleForKey:@"inapCoordinateLong"];
//inapCoordinate=[[CLLocationCoordinate2D alloc] initWithLatitude:lat1 longitude:long1];
CLLocationCoordinate2D new_coordinate = { lat, long1 };
self.inapCoordinate=new_coordinate;
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:PlaceName forKey:@"inapPlaceName"];
[aCoder encodeDouble:inapCoordinate.latitude forKey:@"inapCoordinateLat"];
[aCoder encodeDouble:inapCoordinate.longitude forKey:@"inapCoordinateLong"];
}
This is the usual method.
CLLocation *myLocationToStore = ...; // (a CLLocation object)
NSData *locationData = [NSKeyedArchiver archivedDataWithRootObject:myLocationToStore];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With