iOS 设定值
例子
要在中设置值NSUserDefaults,可以使用以下功能:
迅捷<3
setBool(_:forKey:) setFloat(_:forKey:) setInteger(_:forKey:) setObject(_:forKey:) setDouble(_:forKey:) setURL(_:forKey:)
斯威夫特3
在夫特3的功能的名称被改变为setinsted的的set由类型folloed。
set(_:forKey:)
物镜
-(void)setBool:(BOOL)value forKey:(nonnull NSString *)defaultName; -(void)setFloat:(float)value forKey:(nonnull NSString *)defaultName; -(void)setInteger:(NSInteger)value forKey:(nonnull NSString *)defaultName; -(void)setObject:(nullable id)value forKey:(nonnull NSString *)defaultName; -(void)setDouble:(double)value forKey:(nonnull NSString *)defaultName; -(void)setURL:(nullable NSURL *)value forKey:(nonnull NSString *)defaultName;
用法示例为:
迅捷<3
NSUserDefaults.standardUserDefaults.setObject("Netherlands", forKey: "HomeCountry")
斯威夫特3
UserDefaults.standard.set("Netherlands", forKey: "HomeCountry")
物镜
[[NSUserDefaults standardUserDefaults] setObject:@"Netherlands" forKey:@"HomeCountry"];
自定义对象
要将自定义对象保存到“NSUserDefaults”中,您需要使CustomClass符合“NSCoding”协议。您需要实现以下方法:
迅速
public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey:"name") aCoder.encodeObject(unitId, forKey: "unitId") } required public init(coder aDecoder: NSCoder) { super.init() name = aDecoder.decodeObjectForKey("name") as? String unitId = aDecoder.decodeIntegerForKey("unitId") as? NSInteger }
物镜
- (id)initWithCoder:(NSCoder *)coder { self = [super init]; if (self) { name = [coder decodeObjectForKey:@"name"]; unitId = [coder decodeIntegerForKey:@"unitId"]; } return self; } - (void)encodeWithCoder:(NSCoder*)coder { [coder encodeObject:name forKey:@"name"]; [coder encodeInteger:unitId forKey:@"unitId"]; }