切換視圖我一直在使用Xcode中的〜9月,現在,我即將完成我的應用程序,但有1個小問題...保存數據時的NSKeyedArchiver
背景的一點點。我有一個按鈕,隨機吐出一些數據[在這種情況下的鍛鍊]。在那個窗口中還有一個按鈕來刷新數據並清除標籤。
我想在屏幕上保持randomStretchLabel1,randomStretchLabel2,即使用戶更改視圖或離開應用程序。我希望它保持在屏幕上,只有當用戶點擊randomButton或clearAllWorkouts時才能重新加載。
PIcture of table view to stretchViewController
@interface StretchViewController()
{
NSArray *stretchOptions;
}
- (IBAction)clearAllWorkouts:(id)sender;
- (IBAction)randomStretchButton1:(id)sender;
@property (retain, nonatomic) IBOutlet UILabel *randomStretchLabel1;
@property (retain, nonatomic) IBOutlet UILabel *randomStretchLabel2;
@end
@implementation StretchViewController
@synthesize randomStretchLabel1, randomStretchLabel2;
- (IBAction)clearAllWorkouts:(id)sender {
randomStretchLabel1.text = @"";
randomStretchLabel2.text = @"";
}
- (IBAction)randomStretchButton1:(id)sender {
stretchOptions = [[NSArray alloc]initWithObjects:@"90/90 Hamstring", @"Adductor", @"Adductor/Groin", @"All Fours Quad Stretch",@"Ankle Circles", @"Ankle On The Knee" @"Anterior Tibialis-SMR", @"Arm Circles", @"Behind Head Chest Stretch", @"Brachialis-SMR", @"Calf Stretch Elbows Against Wall", @"Calf Stretch Hands Against Wall", nil];
int labelIndex = rand()%stretchOptions.count;
[randomStretchLabel1 setText:[stretchOptions objectAtIndex:labelIndex]];
int labelIndex2 = rand()%stretchOptions.count;
[randomStretchLabel2 setText:[stretchOptions objectAtIndex:labelIndex2]];
}
改爲下面根據建議,但仍然沒有得到我想要的東西。當我回到表格視圖(所有其他訓練都存儲在其中)時,標籤會自動重置。
- (void)archive
{
[[NSUserDefaults standardUserDefaults] setValue:randomStretchLabel1.text forKey:@"randomStretchLabel1"];
[[NSUserDefaults standardUserDefaults] setValue:randomStretchLabel2.text forKey:@"randomStretchLabel2"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)unarchive
{
randomStretchLabel1.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"randomStretchLabel1"];
randomStretchLabel2.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"randomStretchLabel2"];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setRandomStretchLabel1:nil];
[self setRandomStretchLabel2:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[super dealloc];
}
@end
如果數據非常簡單,NSKeyedArchiver是保持數據和對象圖形最簡單的方法。以下是一個易於閱讀的概述:http://nshipster.com/nscoding/ –
爲什麼核心數據不適合您? –
我也推薦CoreData。您可以將鍛鍊等存儲爲對象,並維護對活動對象的引用。您的視圖/視圖控制器可以在加載時顯示這些活動對象;刷新可能會改變它們。 – sapi