NSArray *arr = [[NSArray alloc] initWithObjects:@"arr1", @"arr2", nil] [mySettingData setObject:arr forKey:@"arrItem"]; [mySettingData setObject:@"admin" forKey:@"user_name"]; [mySettingData setBOOL:@YES forKey:@"auto_login"]; [mySettingData setInteger:1 forKey:@"count"];
NSUserDefaults *mySetting = [NSUserDefaults standardUserDefaults]; NSLog(@"arrItem=%@", [mySetting objectForKey:@"arrItem"]); NSLog(@"user_name=%@", [mySetting objectForKey:@"user_name"]); NSLog(@"count=%d", [mySetting integerForKey:@"count"]);
运行上面的语句后,NSUserDefaults中的数据即被写入到.plist文件中,如果是在模拟器上运行程序,可以在Mac的/Library/Prefereces目录下面找到一个文件名为com.apple.PeoplePicker.plist的plist文件,用Xcode打开该文件,可以看到刚才写入的数据。
@pragma mark -引导页只执行一次
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){ 这一行-->加入引导页[self startYinDaoYe] [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"]; [[NSUserDefaults standardUserDefaults] synchronize]; }
@系统定义的数据类型,NSUserDefault配合NSKeyedArchiver和NSKeyedUnarchiver做本地持久化
这里用数组做个举例:
static NSString *const archiverKey = @"DataArray"; - (void)_testNSKeyedArchiverAndNSKeyedUnarchiver { NSArray *setDataArray = @[@"1",@"2",@"3"]; NSData *archiverData = [NSKeyedArchiver archivedDataWithRootObject:setDataArray]; [[NSUserDefaults standardUserDefaults] setObject:archiverData forKey:archiverKey]; // 切莫忘记,依旧调用 synchronize 立即写入沙盒中 [[NSUserDefaults standardUserDefaults] synchronize]; NSArray *getDataArray = [NSArray new]; NSData *unarchiverData = [[NSUserDefaults standardUserDefaults] objectForKey:archiverKey]; getDataArray = [NSKeyedUnarchiver unarchiveObjectWithData:unarchiverData]; NSLog(@" getDataArray = %@",getDataArray); }
@切记,数组类型为NSArray的时候可以直接getDataArray = [NSKeyedUnarchiver unarchiveObjectWithData:unarchiverData]; 如果数组类型是NSMutableArray,则必须,getDataArray = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:unarchiverData]]; 否则getDataArray为nil
@NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary.
如果把一个自定义的类存到一个NSArray里,然后再存到NSUserDefaults里也是不能成功的。
那怎么办呢?
让这个自定义类实现<NSCoding>协议中的
- (id) initWithCoder: (NSCoder *)coder方法
- (void) encodeWithCoder: (NSCoder *)coder方法,
然后把该自定义的类对象编码到NSData中,再从NSUserDefaults中进行读取。
具体可以回看我的-->数据持久化(一)序列化与反序列化