Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID
Please do not post the same thing multiple times. The board software automatically flags certain posts as needing moderator attention. This happens the most often for new users. I'm pretty sure this is made clear at the time you attempt to post. Posting the same thing over and over again just makes that many more posts the moderators have to weed through later. This makes us sad. Don't make us sad. If your post/thread doesn't appear, just wait a while. Don't post it again. If it hasn't shown up by the next day, then you can try again. I normally go through posts in the mornings, and try to check a few times throughout the day, but I'm not here 24/7. There will typically be a significant delay before posts are approved. Just be patient.

Tutorial #1 : How to use NSUserDefault

IceGameIceGame Posts: 23New Users
Hello,
I made this tutorial on NSUserDefault because , sometimes we want to save a score or see data on two viewcontroller .

In this exemple this is how to save a score and display it in StatsViewController :

Create a property for your NSInteger :

.h
@property (nonatomic) IBOutlet NSInteger myScore;
Now we want to save the score when the player lost :

.m
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:myScore forKey:@"myScore"];
[prefs synchronize];
In your stats view :
.h
- create a label and a property for your integer :
@property (nonatomic) IBOutlet NSInteger score;
@property (nonatomic) IBOutlet UILabel label;

Display your score on the label :
.m
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
score = [prefs integerForKey:@"myScore"];
label.text = [NSString stringWithFormat:@"Score:%d",score];

It's same for NSString :

.h
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
.m
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
Double
.h
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setDouble:3.1415 forKey:@"doubleKey"];
and Float :
.h
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:1.2345678 forKey:@"floatKey"];
.m
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
float myFloat = [prefs floatForKey:@"floatKey"];

So I hope that this tutorial help you ,
you can ask me to make a tutorial on a problem that you have .

IceGame

Replies

Sign In or Register to comment.