//儲存到NSUserDefaults
-(void)saveNSUserDefaults
{
NSString *myString = @"enuola";
int myInteger = 100;
float myFloat = 50.0f;
double myDouble = 20.0;
NSDate *myDate = [NSDate date];
NSArray *myArray = [NSArray arrayWithObjects:@"hello", @"world", nil];
NSDictionary *myDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"enuo", @"20", nil] forKeys:[NSArray arrayWithObjects:@"name", @"age", nil]];
//將上面的物件儲存到NSUserDefaults中
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//除NSNumber需用對應的型別以外,其他的都是使用setObject:forKey:
[userDefaults setInteger:myInteger forKey:@"myInteger"];
[userDefaults setFloat:myFloat forKey:@"myFloat"];
[userDefaults setDouble:myDouble forKey:@"myDouble"];
[userDefaults setObject:myString forKey:@"myString"];
[userDefaults setObject:myDate forKey:@"myDate"];
[userDefaults setObject:myArray forKey:@"myArray"];
[userDefaults setObject:myDictionary forKey:@"myDictionary"];
//建議同步,但是不是必須的
[userDefaults synchronize];
}
//從NSUserDefaults讀取資料
-(void)readNSUserDefaults
{
NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
//讀取數據到各個label中
//讀取整型int類型的數據
NSInteger myInteger = [userDefaultes integerForKey:@"myInteger"];
txtInteger.text = [NSString stringWithFormat:@"%d",myInteger];
//讀取浮點型float類型的數據
float myFloat = [userDefaultes floatForKey:@"myFloat"];
txtFloat.text = [NSString stringWithFormat:@"%f",myFloat];
//讀取double類型的數據
double myDouble = [userDefaultes doubleForKey:@"myDouble"];
txtDouble.text = [NSString stringWithFormat:@"%f",myDouble];
//讀取NSString類型的數據
NSString *myString = [userDefaultes stringForKey:@"myString"];
txtNSString.text = myString;
//讀取NSDate日期類型的數據
NSDate *myDate = [userDefaultes valueForKey:@"myDate"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
txtNSDate.text = [NSString stringWithFormat:@"%@",[df stringFromDate:myDate]];
//讀取數組NSArray類型的數據
NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
NSString *myArrayString = [[NSString alloc] init];
for(NSString *str in myArray)
{
NSLog(@"str= %@",str);
myArrayString = [NSString stringWithFormat:@"%@ %@", myArrayString, str];
[myArrayString stringByAppendingString:str];
// [myArrayString stringByAppendingFormat:@"%@",str];
NSLog(@"myArrayString=%@",myArrayString);
}
txtNSArray.text = myArrayString;
//讀取字典類型NSDictionary類型的數據
NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
NSString *myDicString = [NSString stringWithFormat:@"name:%@, age:%d",[myDictionary valueForKey:@"name"], [[myDictionary valueForKey:@"age"] integerValue]];
txtNSDictionary.text = myDicString;
}
沒有留言:
張貼留言