[英]How to determine what kind of data is stored in NSUserDefaults
I am currently storing an NSUInteger
in NSUserDefaults
to persist data, but I need to move over to an NSObject
that is NSCoding
compliant and that will be stored as NSData
. 我目前在
NSUserDefaults
存储一个NSUInteger
来持久化数据,但是我需要移至一个符合NSCoding
的NSObject
并将其存储为NSData
。 Is there a way to determine whether I am storing an int or an object in my key so that I can accommodate users who have or have not migrated from one persistence type to the other? 有没有一种方法可以确定我是在密钥中存储int还是对象,以便可以容纳已经从一种持久性类型迁移到另一种持久性类型的用户或没有迁移到另一种持久性类型的用户? I know
objectForKey
returns an id, so is this good enough? 我知道
objectForKey
返回一个id,这样够好吗?
- (id) returnStuff {
NSData *data = [myUserDefaults objectForKey:myKey];
if([data isKindOfClass:[NSData class]) {
// then it must be an archived object
return (desiredObjectClass*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
}
else {
NSUInteger returnInt = [myUserDefaults integerForKey:myKey];
return [NSNumber numberWithInteger: returnInt];
}
You can use isKindOfClass:
to treat NSData
specially, as you have done, except I wouldn't bother unboxing the integer only to rebox it. 您可以
isKindOfClass:
使用isKindOfClass:
来对NSData
特殊处理,只不过我不会为将整数重新装箱而烦恼。 The following method handles and returns any type. 以下方法处理并返回任何类型。
Note: there is no need to cast the unarchived data, as the compiler won't care as you are returning id
. 注意:无需强制转换未归档的数据,因为在返回
id
,编译器将不在乎。
- (id)stuffForKey:(NSString *)key {
id value = [[NSUserDefaults standardUserDefaults] objectForKey:key];
if ([value isKindOfClass:[NSData class]]) {
// then it must be an archived object
NSData *dataValue = (NSData *)value;
return [NSKeyedUnarchiver unarchiveObjectWithData:dataValue];
}
return value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.