How to store custom objects in NSUserDefaults

后端 未结 7 1583
悲&欢浪女
悲&欢浪女 2020-11-21 11:48

Alright, so I\'ve been doing some poking around, and I realize my problem, but I don\'t know how to fix it. I have made a custom class to hold some data. I make objects fo

7条回答
  •  孤街浪徒
    2020-11-21 12:20

    Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults to save and retrieve custom objects:

    @interface NSUserDefaults (NSUserDefaultsExtensions)
    
    - (void)saveCustomObject:(id)object
                         key:(NSString *)key;
    - (id)loadCustomObjectWithKey:(NSString *)key;
    
    @end
    
    
    @implementation NSUserDefaults (NSUserDefaultsExtensions)
    
    
    - (void)saveCustomObject:(id)object
                         key:(NSString *)key {
        NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
        [self setObject:encodedObject forKey:key];
        [self synchronize];
    
    }
    
    - (id)loadCustomObjectWithKey:(NSString *)key {
        NSData *encodedObject = [self objectForKey:key];
        id object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
        return object;
    }
    
    @end
    

    Usage:

    [[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];
    

提交回复
热议问题