我正在構建一個水龍頭計數的應用程序(例如:進入房間的人)。 主要目標是能夠有多個計數器(例如:主房間櫃檯,白色櫃檯櫃檯,綠色房間櫃檯等)。iOS的水龍頭計數器應用程序 - 多個計數器
該應用程序包括:
計數器的列表 - CounterListTableViewController,具有功能 在列表
創建新的項目(計數器)計數器頁 - RowCounterViewController
我困在此刻:在TableViewController中保存計數參考項目的計數器數量。
可能的解決方案:
保存所有數數到一個數組 - 我不知道如何,但(一個完整的初學者)。
按照KudoCC在下面的答案中的建議,用NSUserDefaults的索引保存所有計數數字。
謝謝!
最後編輯:
#import "RowCounterViewController.h"
@interface RowCounterViewController()
@end
@implementation RowCounterViewController
-(IBAction)plus {
counter=counter + 1;
count.text = [NSString stringWithFormat:@"%i",counter];
}
-(IBAction)minus {
counter=counter - 1;
count.text = [NSString stringWithFormat:@"%i",counter];
}
-(IBAction)reset {
counter=0;
count.text = [NSString stringWithFormat:@"%i",counter];
}
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCount)
name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCount)
name:UIApplicationWillTerminateNotification object:nil];
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"saveCount"] ;
NSUInteger count = [dict objectForKey:@(itemIndex)] ;
//NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//NSString *countString = [userDefaults objectForKey:@"saveCount"];
//NSLog(@"Your Count: %@",count);
//checking if data in user defaults is not empty
//if(countString.length>0)
//{
// count.text = [NSString stringWithFormat:@"%i",counter];
// counter = [countString intValue];
//}
//else
//{
// //for first time
// counter = 0;
// count.text = @"0";
//}
//counter=0;
//count.text = @"0";
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)saveCount {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"saveCount"] ;
NSMutableDictionary *mDict = [dict mutableCopy] ;
[mDict setObject:@(count) forKey:@(itemIndex)] ;
[[NSUserDefaults standardUserDefaults] setObject:mDict forKey:@"saveCount"] ;
[[NSUserDefaults standardUserDefaults] synchronize] ;
}
//- (void)dealloc {
// [self saveCount] ;
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before
navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
爲什麼要將計數保存爲字符串而不是整數?此外,如果你想多個計數器,那麼你將需要存儲一個數組,而不是一個單一的值 – Paulw11
@ Paulw11多數民衆贊成那是因爲我是一個完整的初學者:)你能建議如何改變整數?我想弄清楚如何使用Ian Lan提到的方法來存儲數組 – dicobraz
您可以調用'setInteger:forKey:'和'getIntgerForKey:'而不是set/get對象 – Paulw11