简体   繁体   English

将CLLocationCoordinate2D存储到NSUserDefaults

[英]Store CLLocationCoordinate2D to NSUserDefaults

I am new to iphone development, and i want to store CLLocationCoordinate2D object to NSUserDefaults . 我是iphone开发的新手,我想将CLLocationCoordinate2D对象存储到NSUserDefaults I am Trying 我在尝试

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

But it gives error 'Sending CLLocationCoordinate2D to parameter of incompatible type id' 但它给出错误'将CLLocationCoordinate2D发送到不兼容类型id的参数'

So How to store CLLocationCoordinate2D into NSUserDefaults ? 那么如何将CLLocationCoordinate2D存储到NSUserDefaults Thanks. 谢谢。

As pdrcabrod said, 正如pdrcabrod所说,

"A default object must be a property list, that is, an instance of NSData , NSString , NSNumber , NSDate , NSArray , or NSDictionary ." “默认对象必须是属性列表,即NSDataNSStringNSNumberNSDateNSArrayNSDictionary的实例。”

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"]);

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)];

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. NSUserDefaults类提供了访问常用类型(如浮点数,双精度数,整数,布尔值和URL)的便捷方法。 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. 默认对象必须是属性列表,即(或集合的实例组合)的实例:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。 If you want to store any other type of object, you should typically archive it to create an instance of NSData 如果要存储任何其他类型的对象,通常应将其存档以创建NSData实例

See: NSUserDefaults 请参阅: NSUserDefaults

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. 我希望它有所帮助。

As others have said, first convert it into a Dictionary or Data object and then save it as you normally would. 正如其他人所说,首先将其转换为DictionaryData对象,然后像往常一样保存它。 In Swift I highly recommend using extensions. 在Swift中,我强烈建议使用扩展。 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]!)
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM