首页 > 代码库 > NSUserDefault存储类

NSUserDefault存储类

  1. 类要实现NSCoding协议
    实现encodeWithCoderinitWithCoder方法
  2. 先把类的instance archive成NSData,然后存起来

    TGTest *tt = [TGTest new];
    tt.num = 3;
    NSData *dd = [NSKeyedArchiver archivedDataWithRootObject:tt];
    [[NSUserDefaults standardUserDefaults] setObject:dd forKey:@"objtest"];
    
  3. 读数据时,读出NSData,然后unarchive得到instance。

    NSData *dd = [[NSUserDefaults standardUserDefaults] objectForKey:@"objtest"];
    @try
    {
        TGTest *tt= [NSKeyedUnarchiver unarchiveObjectWithData:dd];
    }
    @catch (NSException *exception)
    {
        NSLog(@"%@",exception);
    }
    @finally
    {
    
    }
    

NSUserDefault存储类