首页 > 代码库 > <01>数据存储 - NSUserDefaults <01>

<01>数据存储 - NSUserDefaults <01>

//将NSUserDefaults的实例化定义成宏
#define USER_DEFAULT [NSUserDefaults standardUserDefaults]
 
 
 
  /*NSUserDefaults是一个单例,适合存储轻量级的本地数据,一些简单的数据(NSString类型的)例如密码,网址等 在整个程序中只有一个实例对象,他可以用于数据的永久保存,一般用来存储简单的信息(支持的数据类型有:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL)。
     */
   
   
    //实例化
    // NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    //存数据
    //类型-> NSString
    NSString *userName = @"用户名";
    NSString *userUid = @"用户id";
    [USER_DEFAULT setObject:userName forKey:@"name"];
    [USER_DEFAULT setObject:userUid forKey:@"uid"];
    [USER_DEFAULT synchronize];//同步存储到磁盘中(可选)
    //取数据
    NSString *_userName = [USER_DEFAULT objectForKey:@"name"];
    NSString *_userUid = [USER_DEFAULT objectForKey:@"uid"];
    NSLog(@"_userName = %@,_userUid = %@",_userName,_userUid);
   
    //清除指定数据
    [USER_DEFAULT removeObjectForKey:@"name"];
    [USER_DEFAULT removeObjectForKey:@"uid"];
    //清除所有数据
    NSString *bundle = [[NSBundle mainBundle] bundleIdentifier];
    [USER_DEFAULT removePersistentDomainForName:bundle];
   
   
   
    //存储时,除NSNumber类型
    //1、存取->NSInteger
    NSInteger integer = 1;
    [USER_DEFAULT setInteger:integer forKey:@"integer"];
    [USER_DEFAULT integerForKey:@"integer"];
    //2、存取->float
    float flaot = 1.0;
    [USER_DEFAULT setFloat:flaot forKey:@"flaot"];
    [USER_DEFAULT floatForKey:@"flaot"];
    //3、存取->BOOL
    BOOL isBool = YES;
    [USER_DEFAULT setBool:isBool forKey:@"isBool"];
    [USER_DEFAULT boolForKey:@"isBool"];
    //4、存取—>Double
    double doulbe = 1.2;
    [USER_DEFAULT setDouble:doulbe forKey:@"doulbe"];
    [USER_DEFAULT doubleForKey:@"doulbe"];
   
    /*NSUserDefaults 存储的对象全是不可变。要存储一个 NSMutableArray 对象,必须先创建一个不可变数组(NSArray)再将它存入NSUserDefaults中去。
    */
     //7、存取—>NSArray
    NSMutableArray *marry = [NSMutableArray arrayWithObjects:@"obj_one",@"obj_two", nil];
    NSArray *arry = [NSArray arrayWithArray:marry];
    [USER_DEFAULT setObject:arry forKey:@"arry"];
    [NSMutableArray arrayWithArray:[USER_DEFAULT arrayForKey:@"arry"]];
     //8、存取—>NSDictionary
    NSDictionary *diction = [NSDictionary dictionaryWithObjectsAndKeys:@"Jack",@"name",@"18",@"age", nil];
    [USER_DEFAULT setObject:diction forKey:@"diction"];
    [USER_DEFAULT dictionaryForKey:@"diction"];
     //9、存取—>NSData
   
    UIImage *image = [UIImage imageNamed:@""];
    NSData *imagedata = http://www.mamicode.com/UIImageJPEGRepresentation(image, 1.0);//UIImage-NSData
    [USER_DEFAULT setObject:imagedata forKey:@"imagedata"];
    NSData *dataimage = [USER_DEFAULT dataForKey:@"imagedata"];
    UIImage *_image = [UIImage imageWithData:dataimage];//NSData-UIImage
    NSLog(@"获取image->%@",_image);
   
   
   
    
 

<01>数据存储 - NSUserDefaults <01>