简体   繁体   中英

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 . 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? I know objectForKey returns an id, so is this good enough?

- (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. 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)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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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