Advertise here




Advertise here

Howdy, Stranger!

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

Tutorial #1 : How to use NSUserDefault

IceGameIceGame Posts: 29New Users @
edited July 2012 in iPhone SDK Tutorials
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.