gpt4 book ai didi

ios - 如何确定 NSUserDefaults 中存储的数据类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:58:57 26 4
gpt4 key购买 nike

我目前正在 NSUserDefaults 中存储一个 NSUInteger 以保存数据,但我需要转移到一个 NSObject NSCoding 兼容,将存储为 NSData。有没有一种方法可以确定我是在我的 key 中存储一个 int 还是一个对象,以便我可以容纳已经或没有从一种持久性类型迁移到另一种持久性类型的用户?我知道 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];
}

最佳答案

您可以使用 isKindOfClass: 来特殊处理 NSData,就像您所做的那样,除了我不会费心拆箱整数只是为了重新装箱。以下方法处理并返回任何类型。

注意:不需要强制转换未归档的数据,因为编译器不会关心您返回的 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;
}

关于ios - 如何确定 NSUserDefaults 中存储的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34341310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com