Re: [iPhone] Application running for the very first time...
Re: [iPhone] Application running for the very first time...
- Subject: Re: [iPhone] Application running for the very first time...
- From: Steve Christensen <email@hidden>
- Date: Wed, 07 Oct 2009 10:33:44 -0700
On Oct 1, 2009, at 10:57 PM, James Lin wrote:
Thank you for the code snipet, but I am confused at the logic here...
the following code will be executed EVERY time the program runs,
right?
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]
initWithCapacity:10];
[dictionary setObject: [NSNumber numberWithBool:YES]
forKey:@"PIFirstRun"];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
[dictionary release];
so [dictionary setObject: [NSNumber numberWithBool:YES]
forKey:@"PIFirstRun"] will run EVERYTIME the program runs?
Wouldn't that set my PIFirstRun to YES every time the user launch
my application?
The user defaults are just that: default values. They provide the
values that are returned for a key by NSUserDefaults until the value
for that key is modified by your application. So, yes, the code above
will be run every time but it doesn't affect any modified keys. As
soon as a key's value is modified, that new value is added to the
application's preference file and will be used from that point
forward. If the preferences file is ever deleted, your application
will go back to using the default values until they are modified.
So you could think of the behavior of [[NSUserDefaults
standardUserDefaults] boolForKey:@"PIFirstRun"] as:
if (PIFirstRun key exists in my app's preferences)
return value of key from app's preferences;
else
return value of key from defaults dictionary;
In that case....
if ([[NSUserDefaults standardUserDefaults]
boolForKey:@"PIFirstRun"] == YES){
[[NSUserDefaults standardUserDefaults] setBool:NO
forKey:@"PIFirstRun"];
//first run
[userDefaults setInteger:5 forKey:@"myIngeter"];
}
will reset my "myInteger" to 5 EVERY single time?
Yes, because you're modifying the value of that key every time.
What if all i want is to set "myInteger" to 5 the very first time
my application lunches and ONCE ONLY?
Add it to the defaults dictionary:
NSDictionary* defaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], @"PIFirstRun",
[NSNumber numberWithInt:5], @"myInteger",
nil];
[[NSUserDefaults standardUserDefaults] defaults];
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden