[英]Can I save an NSUserDefault value based on another NSUserDefault value?
Here is what I'm trying to achieve: I've location saved in NSUserDefaults. 这是我要实现的目标:我已将位置保存在NSUserDefaults中。 Now with this added in NSUserDefault user will select a value and I want to save this value in for this location.
现在,通过在NSUserDefault中添加此值,用户将选择一个值,并且我想将此值保存在该位置。 So when user selects that location again I can get the selected location back.
因此,当用户再次选择该位置时,我可以取回所选位置。
So this value is different for different locations and user can also change them at anytime. 因此,此值对于不同的位置是不同的,用户也可以随时更改它们。 i want to know is it possible to do so?
我想知道是否可以这样做? If not then what will be the optimized way to do this?
如果没有,那么优化的方法是什么? I haven't started this implementation yet so there is no code.
我尚未开始此实现,因此没有代码。
If you want to save a dictionary: 如果要保存字典:
let dict:[String:String] = ["key":"value"]
// set multiple values into a specific location
UserDefaults.standard.set(dict, forKey: "locationA")
// get the values for a given location
let result = UserDefaults.standard.value(forKey: "locationA")
print(result!)
or a simple value 或一个简单的值
let value = "value"
// set simple value into a specific location (for key)
UserDefaults.standard.set(value, forKey: "locationA")
// get the value for a given location
let result = UserDefaults.standard.value(forKey: "locationA")
print(result!)
It is possible to do this. 可以这样做。 For each location you could create a two-item
NSArray
in which the first item is the location, and the second item is the value. 对于每个位置,您可以创建一个包含两项的
NSArray
,其中第一项是位置,第二项是值。 For example: 例如:
NSArray *locationData = @[location, value];
You would keep an NSArray
of those two-item NSArrays
, and save that to NSUserDefaults
: 您将保留一个包含两个项目
NSArrays
的NSArray
,并将其保存到NSUserDefaults
:
NSArray *allLocations = @[@[location1, value1], @[location2, value2], ...];
[[NSUserDefaults standardUserDefaults] setObject:allLocations forKey:@"LocationData"];
To look up the value for a particular location you would walk through the array (this code considers any location within 100m to be the same location): 要查找特定位置的值,您需要遍历数组(此代码将100m内的任何位置都视为相同位置):
- (id)valueForLocation:(CLLocation *)location {
for (NSArray *locInfo in allLocations) {
CLLocation *loc = (CLLocation *) locInfo[0];
if ([location distanceFromLocation:loc] < 100) {
return locInfo[1];
}
}
return nil;
}
Another way to do this is to store this information in a dictionary, keyed off the location. 执行此操作的另一种方法是将该信息存储在字典中,从该位置键入。 You can't use a
CLLocation
as a key directly, but you put a CLLocation
's coordinates into an NSValue
and use that. 您不能直接将
CLLocation
用作键,而是将CLLocation
的坐标放入NSValue
并使用它。 For more details see using CLLocation objects as keys in dictionary . 有关更多详细信息,请参见在字典中使用CLLocation对象作为键 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.