Increment integer in NSUserDefaults
No but if you do this a lot it might make a nice extension, something like this.
extension NSUserDefaults {
class func incrementIntegerForKey(key:String) {
let defaults = standardUserDefaults()
let int = defaults.integerForKey(key)
defaults.setInteger(int+1, forKey:key)
}
}
Usage like this
NSUserDefaults.incrementIntegerForKey("counter")
Swift, iOS- NSUserDefaults for days active? Only increment int when it is the first time they opened app on THAT DAY?
First of all this NSDate
extension will make things easier
extension NSDate {
var isToday: Bool {
let now = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: NSDate())
let this = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
return now.year == this.year && now.month == this.month && now.day == this.day
}
}
Now your extension can be written as follow
extension NSUserDefaults {
class func incrementIntegerForKey(key:String) {
let lastIncreased = NSUserDefaults.standardUserDefaults().valueForKey("lastCheck_\(key)")
let alreadyIncreasedToday = lastIncreased?.isToday ?? false
if !alreadyIncreasedToday {
let counter = NSUserDefaults.standardUserDefaults().integerForKey(key)
NSUserDefaults.standardUserDefaults().setInteger(counter + 1, forKey: key)
NSUserDefaults.standardUserDefaults().setValue(NSDate(), forKey: "lastCheck_\(key)")
}
}
}
Please note that this
incrementIntegerForKey
is NOT thread safe.
How do I increment and save a int value in Swift?
You are declaring a new var deathScore everytime, initialized with 0 and incrementing it. It will always be 1.
UserDefaults.standard.set(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths")+1, forKey: "saveNumberOfDeaths")
deathLabel.text = String(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths"))
Saving incremental int variable
Try adding:
[[NSUserDefaults standardUserDefaults] synchronize];
After each time you change the value of your integer.
Quoting Apple's documentation on synchronize
:
Writes any modifications to the persistent domains to disk and updates
all unmodified persistent domains to what is on disk.
http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/synchronize
So with this modification, your final code should look like this:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:@"AppCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
EDIT: Actually on second thought, give this a try:
I think the problem is using i++ assumes that the application will always be able to keep track of the count, and every time you re-enter the application i gets reset.
The following works, I just tested it.
if (![[NSUserDefaults standardUserDefaults] integerForKey:@"AppCount"]) {
[[NSUserDefaults standardUserDefaults] setInteger:i forKey:@"AppCount"];
}else{
[[NSUserDefaults standardUserDefaults] setInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@"AppCount"] + 1 forKey:@"AppCount"];
}
[[NSUserDefaults standardUserDefaults] synchronize];
How do I Increment Integer and save it for use when program is re-run?
You can use NSUserDefaults
to store int
s and other basic types (BOOL
, float
, NSString
, NSArray
).
For example, you can retrieve the int
using
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
int orderNumber = [prefs integerForKey:@"orderNumber"];
and then save the int
using
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:orderNumber forKey:@"orderNumber"];
When necessary, you can also call
[prefs synchronize];
to ensure that you are accessing the most up to date information. This is especially useful if you are accessing this int
in multiple places in your app.
How to save integer value to NSuserDefault like sqlite?
Try to implement like this..Sure it'll help...
@implementation ClassA
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[NSUserDefaults standardUserDefaults]setInteger:100 forKey:@"save_Interger_Value_For_Formula_One"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
@end
@implementation ClassB
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
int B = [[[NSUserDefaults standardUserDefaults] integerForKey:@"save_Interger_Value_For_Formula_One"] integerValue];
NSLog(@"Interger Value %d",b);
}
Increment UILabel from UserDefaults value - Swift
You never set pointScore1
to the value retrieved from UserDefaults
.
Start by retrieving and storing the Int
value, not a String
.
override func viewDidLoad() {
super.viewDidLoad()
pointScore1 = UserDefaults.standard.integer(forKey: "points1")
teamOnePoint.text = "\(pointScore1)"
}
@IBAction func teamOneButtonPressed(_ sender: Any) {
pointScore1 += 1
teamOnePoint.text = "\(pointScore1)"
UserDefaults.standard.set(pointScore1, forKey: "points1")
}
Note that after a fresh install of the app, the initial value will be 0
. Deal with that as desired.
Related Topics
How to Add Floating Button on Top of the Uitableview
Create a Swift Dictionary Subclass
How to Turn Off Color Literals in Xcode
Cannot Subscript a Value of Type '[String:String]' with an Index of Type 'String'
Refreshing Auth Token with Moya
Is This Safe to Call Wait() of Dispatchsemaphore Several Times at One Time
How to Initialise a New Nsdocument Instance in Swift
App Crashes from IPA File But Runs Fine from Xcode
How to Get the Kvc-String from Swift 4 Keypath
Pop View Controller Using Screen Edge Pan Gesture Recogniser Not Following the Thumb
How to Suppress a Specific Warning in Swift
More Concise Way to Nest Enums for Access by Switch Statements in Swift
How to Have Arview and Arscnview Coexist
What Does a "Do Statement" Without Catch Block Mean
Swiftui Tabbar: Action for Tapping Tabitem of Currently Selected Tab to Reset View
Swift and Objectmapper: Nsdate with Min Value