- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. //分組按鈕 UISegmentedControl* seg = [[UISegmentedControl alloc] init] ; seg.frame = CGRectMake(50, 160, 220, 40); seg.backgroundColor = [UIColor orangeColor]; [seg insertSegmentWithTitle:@"寫入數據" atIndex:0 animated:NO] ; [seg insertSegmentWithImage:[UIImage imageNamed:@"2"] atIndex:0 animated:YES]; [seg insertSegmentWithTitle:@"讀出數據" atIndex:1 animated:NO] ; [seg setBackgroundImage:[UIImage imageNamed:@"2"] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault]; [seg addTarget:self action:@selector(segChange:) forControlEvents:UIControlEventValueChanged] ; [self.view addSubview:seg] ; } -(void) segChange:(UISegmentedControl*) seg { //寫入數據 if (seg.selectedSegmentIndex == 0) { //獲取用戶默認數據對象 //儲存用戶的某些小型數據,例如用戶名,好友列表...... //單例模式:standardUserDefaults得到整個項目中惟一的數據存儲對象 NSUserDefaults* ud = [NSUserDefaults standardUserDefaults] ; //存入一個字符串 [ud setObject:@"張1231" forKey:@"name01"] ; //存入一個整形對象 [ud setInteger:25 forKey:@"age"] ; [ud setBool:YES forKey:@"sex"] ; //建立數組,數據內容爲字符串 NSArray* array = [NSArray arrayWithObjects:@"1001", @"1002", @"1003", nil] ; //array數組中的內容爲NSString,NSNumber [ud setObject:array forKey:@"array"] ; //將數據從內存寫入硬盤文件中 [ud synchronize] ;//同步 NSLog(@"讀入數據"); } //讀出數據 else if(seg.selectedSegmentIndex ==1) { //啓動程序時,若是默認數據文件中有數據 //先將數據讀入到內存中 NSUserDefaults* ud = [NSUserDefaults standardUserDefaults] ; NSString* name = [ud objectForKey:@"name01"] ; NSInteger age = [ud integerForKey:@"age"] ; BOOL sex = [ud boolForKey:@"sex"] ; NSArray* array = [ud objectForKey:@"array"] ; NSLog(@"獲取數據"); NSLog(@"sex = %d",sex); NSLog(@"name = %@",name) ; NSLog(@"age = %ld",age) ; NSLog(@"array = %@",array); } }