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"];
  1. 读数据时,读出NSData,然后unarchive得到instance。
    NSData *dd = [[NSUserDefaults standardUserDefaults] objectForKey:@"objtest"];
    @try
    {
        TGTest *tt= [NSKeyedUnarchiver unarchiveObjectWithData:dd];
    }
    @catch (NSException *exception)
    {
        NSLog(@"%@",exception);
    }
    @finally
    {
        
    }

你可能感兴趣的:(NSUserDefault存储类)