iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
October 3rd, 2008 Posted by: (ELC) - posted under:Tutorials

In this tutorial, I will be showing you how you can save and retrieve different types of data using the NSUserDefaults object.  Saving this way is great for when you want to save small amounts of data such as High Scores, Login Information, and program state.

Saving to the NSUserDefaults is great because it does not require any special database knowledge.  So if you don’t want/have an SQLite3 database for your app, this would be the way to go.

In this tutorial, I do the following things:

Start With A View Based Application

This is done so we can start with a blank view.  Since we won’t require any special functionality from our User Interface, this will be perfect.

Set Up IBOutles And An IBAction

We need to set up an IBOutlet for the UILabel and UITextField so that we can interact with the interface in code.  The IBAction (updatePrefs) gets connected to our UIButton that we will add to the Interface. So when the user presses the button, this method will get called and save their data.

Create The Interface In Interface Builder

The interface for this application is pretty simple.  It only requires a UILabel, UIButton, and a UITextField.  Drag each of these components on to your View.

Connect The UI Components To Your Outlets/Action

If you are unfamiliar with what is happening here, read the tutorial Connecting Code To An Interface Builder View. We are simply making the connections between our UIComponents to the code.  This will allow us to interact with them.

Implement The UpdatePrefs Method

This is where the NSUserDefaults actually get saved.  In this method we perform the following tasks:

  • Get reference to the NSUserDefaults object – This is done so we can call methods on it to save our data
  • call the setObject forKey method – This allows us to save a string for a given key.  The key is just a string value that we will use to look up our data.
  • calling the resignFirstResponder method on the UITextField to hide the keyboard when the button (or return) is pressed
  • Update the message text in the label to read “Application Preferences Saved” to notify the user that their preferences have been saved.

Implement The ViewDidLoad Method

We simply start by uncommenting this method.  It gets called after the view loads (all components have been loaded and drawn).  What we want to do in this method is to retrieve the saved NSUserDefault with the key @”greeting”.  This will get the saved name that the user specified.  If this variable is set to nil, then this is the first time the application has been run (or the user never saved their name).

Here are the steps that are taken in this method:

  • Get a Handle to the NSUserDefaults object
  • Retrieve the saved username by calling the getObject method and passing in the key @”greeting”
  • Check if the saved username is nil – If so, display the default welcome message (Welcome guest)
  • If the username is not nil, construct a new string with it using the initWithFormat constructor.  This will allow us to append the username on to the message “Welcome”.  initWithFormat takes 1 or more args.  The first is the format of the string. In our case its @”Welcome %@!”. This is saying replace the “%@” with a string (which is the next parameter).  If you have ever written in C, this is essetially the sprintf method.
  • Once this string is build, we assign it to name.text to update the label

Here is a quick reference for some of the things you can do with NSUserDefaults

Saving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];

// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];

// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];

// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];

Retrieving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"
keyToLookupString"];

// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"
integerKey"];

// getting an Float
float myFloat = [prefs floatForKey:@"
floatKey"];

If you have any questions or comments, feel free to leave them in the comments section of this post, or post them in the forum. Also be sure and subscribe to the RSS Feed as I will be adding tutorials often.  You can also download the sample code here. Happy iCoding!

  • Bart

    Thanks for the tutorials :-) One question… if you are using initWithFormat, and not releasing it, aren’t you leaking memory? Wouldn’t [NSString stringWithFormat:...] be a better choice?

  • http://www.icodeblog.com Brandon

    Good catch, I should have released this, but I was overcome with laziness…lol I’ll be sure to include the release stuff in future tutorials. Thanks for pointing this out.

  • mark

    These tutorials have been wonderful! Thanks!

    Could you add screen shots to the text you’ve added to the videos? I prefer the written tutorials since I can code while scrolling through the text. (The videos are nice for an overview but following along with them while coding is difficult.) Adding screen shots to the written portion of the video tutorials would be the best of both worlds.

    Thanks for putting all this together!

    – mark

  • http://www.theluiz.com theluiz

    hey!
    thanks for the tutorial, and i just wanted to know how to tie this in with an array of objects? ( the one u wrote about here http://is.gd/3uOi ) so that when the application gets loaded, the same array and therefore the same tableview is present? thanks!

  • http://sanchinsystems.com Joe

    Best iphone sdk tut I’ve seen. Thanks for sharing!

  • mek

    Amazing Tutorial

    Brandon, is it possible to do another Sqlite3 tutorial, but instead of a todo program, just a standard contacts type app, with the instruction on how to Sort them and do a table search on them

    example:

    Search
    —————
    A
    ……Adam
    ……Alex
    B
    ……Bob
    C
    ……Candy

    and then when the click on the name, it opens another view that displays some of their contact information

    thanks

  • http://www.losectrl-gaincommand.com cruffenach

    Nice tutorial. Definitely makes the daunting NSUserDefaults class very approachable. Thanks Man!

  • http://fernyb.net fernyb

    Good job! I like this tutorials especially with video.

  • http://web.mac.com/ostros/iWeb/iPhone%20Apps%20Entre%20Pilotes/HOME%20%28FR%29.html Serge ostrowsky

    Bravo Brandon !

    @Mek:

    I don’t think Brandon has the time to develop exactly the App you want…
    With his tutorials, you now have all you need to write it yourself !
    And you will be even more proud of the result !

    happy hunting !

  • yali900@gmail.com

    Hi, Brandon, Nice video tutorial, which makes it easy to follow

  • Yali

    Hi, Brandon, I have some problems after following your video tutorials, please help me figure out what’s wrong.
    1. it does not work, when I relaunch the app it still says welcome guest. when I debug it and add following statement following your statement: greeting.text = [[NSString alloc] initWithFormat:@”Welcome %@!”,greetName];

    name.text=greetName;

    the name field is populated with the name I input last time.

    it means that the app did retrieve the name correctly, but the “[NSString alloc] initWithForma… ” did not do its job. Do you know why.

    2. when I download your sample code and run, I got following compiling error:
    Checking Dependencies
    error: There is no SDK with specified name or path ‘Unknown Path’
    error: There is no SDK with specified name or path ‘Unknown Path’
    Build failed (1 error)

    What could possibly the cause ?

    Thanks

  • http://www.icodeblog.com Brandon

    @Yali,

    Do you have the latest version of the SDK?

  • screem

    Again a very nice clean tutorial that is very easy to follow. I really look forward to all your future tutorials.

    I hope that this site gets more communal since the NDA has now lifted. Let all help this site rise to the top!!

  • bearc0025

    Awesome again! Thanks!

    A couple shortcuts for anyone that doesn’t know them (and will love them).

    1. cmd+alt/option+up arrow = toggle btwn .m and .h of a class
    2. ctrl+/ = skip to next parameter in coding a message send (not sure if that’s the best way to describe it – for an example watch the video – about 2/3rds thru, Brandon calls prefs setObject:forKey – he clicks on the second parameter to highlight it and type over. ctrl+/ does that for you. :)

    THANKS Brandon!

  • http://www.icodeblog.com Brandon

    @screem,

    thanks for the support. I really do hope to establish a great development community here. It seems that many sites are trying to be the official “iphone forums/community”…If iCodeBlog is to ever be like that, we need to get the forums a little more active. There is over 200 members so far, which is a really good start. Hopefully developers will start linking here more in their blog posts. This will really drive traffic and help the community.

    @bearc

    Those are great hints. Thank you for posting them. Would you mind posting them in the tips & tricks section of the forum. I’m sure they would get a lot of exposure there and help many people out. Thanks again…

  • http://www.theluiz.com theluiz

    hey!
    thanks for the tutorial, and i just wanted to know how to tie this in with an array of objects? ( the one u wrote about here http://is.gd/3uOi ) so that when the application gets loaded, the same array and therefore the same tableview is present?

  • http://www.icodeblog.com Brandon

    @theluiz,

    I’m not sure this is the bes solution for storing arrays. If you want to store arrays, I would recommend using a SQLite3 database.

    You could “ghetto rig” this by doing something like

    *This is just pseudocode

    for(i = 0 to array.length)
    key = “arrayKey” . i
    [prefs setObject:array[i] forKey:key];
    end

    Then you must also store the length of the array…

    [prefs setInteger:array.length forKey:@"arrayLength"];

    Does that make sense?

  • Yali

    Hi, Brandon, I think I have the latest SDK. I downloaded sdk on July 15. I ‘m wondering if others have the same problem as I do with problem 1:

    1. it does not work, when I relaunch the app it still says welcome guest. when I debug it and add following statement following your statement: greeting.text = [[NSString alloc] initWithFormat:@”Welcome %@!”,greetName];

    name.text=greetName;

    the name field is populated with the name I input last time.

    it means that the app did retrieve the name correctly, but the “[NSString alloc] initWithForma… ” did not do its job. Do you know why.

  • David Field

    Will you be able to redo the last two tutorials (the video ones) in the same writen format as the previous ones – it is much easier to study from. The video is still though a great help.

  • David Field

    One concept which is still not clear to me is how these files relate to each other:
    * ‘File’s Owner’ in the .xib file
    * Delegate files
    * Controller files
    If you can clarify the roles and relationships of these files it would be a great help. And thank you very much for the tutorials, it is the best stuff out there.

  • http://www.icodeblog.com Brandon

    @David,

    I don’t have much time to re-do the video tutorials as text. I decided to do video as it provides a much better visual aid than text. I do try to provide some supplemental text explaining why each step is necessary under the video.

    Delegate Files – Each app has one delegate. The delegate is where the app begins execution. If you open up main.m, it calls you appDelegate to start execution.

    Controller – These are usually viewControllers. They are for the purpose of interfacing your interface with your views.

    File’s Owner – This is the bridge between your viewController and Interface Builder. It provides a way for us to connect the view to the IBOutlets and IBActions in Interface Builder.

    I hope these explanations are clear. Thanks for reading…

  • Ryan Brown

    I have to say, I definitely prefer the old style to the new video tutorials.

  • Marco from Ecuador

    Hi. I was just wondering if anybody has the programming code to create a simple ebook…. I would like to share some texts but I am a newby in programming for the iphone.

  • Yali

    I like the video tutorial much more than old style. It is straight forward and easy to understand what need to be done rather than trying to understand what to be done and how it is done through reading.

  • Brendan

    For some reason the defaults for my App don’t load on first launch. They will load if I visit Settings>My App Settings, then re-launch my App.

    Any ideas? I tried invoking updatePrefs in viewDidLoad, but that only updated the Switches and not the TextFields.

    I’m really pulling my hair out, since it seems like the whole viewDidLoad should load the DefaultValues.

    Help?

  • http://www.dr-leech.com.ar/ Leandro

    Fantastic! I was looking for that!

    Thank you!

  • SM

    This might sound very silly question. However I see a big Q with a question mark on it where the video should be.
    What software am i missing?

    Please help

  • http://www.icodeblog.com Brandon

    It’s not a silly question. It means you need to get the latest version of quicktime. All of my tutorials are .mov so they require quicktime to play.

  • http://devirtu.com ahot

    Thanks! There is so few information in the net..
    Your topic was very useful for me.

  • Scott

    Thanks for yet another brilliant tutorial Brandon.
    Forget going to college, you should be working at Apple teaching people how to program the iPhone :-)

  • ter

    fantastic tutorial. very concise & very well paced.

    one question though :

    initWithFormat:@”Welcome %@!” ,greetName];

    % AT !

    you said “% Ampersand ” in the audio. isn’t it %@, not %&?

    thanks again for the tutorials.

    ~t

  • http://www.icodeblog.com Brandon

    @ter

    Hahah you’re right. Consider it a “verbal typ-o”. Good catch… Thanks for reading

  • John

    Hi Brandon,

    I’ve used this tutorial as the basis for adding a settings view to my app which works well. Basically the user needs to choose from a set of values similar to a “select” in HTML so I use a UIPIckerView.

    I’ve started to move most of my options to settings.bundle but and have most things working except for getting the selected value and title back from a “PSMultiValueSpecifier”.

    Any suggestions ?

  • http://www.i-bukmacher.pl Bukmacher

    Ciekawy post, dodalem twoj blog do ulubionych, bede tu teraz wpadal czesciej, pozdrawiam

  • Peter

    Great tutorial. I have a question with regards IBOutlets, @properties, @synthesize. Is it really necessary to add properties for IBOutlets. Seems to work without these.

    Using latest version of SDK.

    Regards Peter.

  • chris

    Thank you for the great tutorials! I’m completely new to coding so I’m slowly making my way through them all.

    Question about this one:

    Why is it after I enter my name and click done the app goes directly to “Your preferences have been saved!” without having pressing the “Update Preferences” button?

    I thought maybe i had screwed something up, but it does the same thing when i compile your source as well.

    Am I missing something?

    -chris

  • http://www.icodeblog.com Brandon

    @chris,

    This is the way I set it up. When the “Return” button is pressed on the keyboard, it calls the same function that gets called when you tap the “Update Preferences” button.

    If you don’t want this functionality, skip the step where i make this connection in Interface Builder.

  • Wolfgang

    Great tutorial! You saved me a lot of time. Thank you very much. Greetings from Germany. Wolfgang.

  • gopi

    Hi all,

    i have face some problem for save the Data from using Sqlite. Anybody know tell me the answer.

    Thanks for all.

  • Tarun sharma

    hello brandon

    i hav just started working on i phone application and found this site very usefull .i m really very thankfull to u and will try my best to provide the resourecs to this site.thanks again buddy

  • Tarun sharma

    hello

    cn some one post a sample application of NSUrlConnection to download and post data to/from server

  • http://susan@codeblog.com susan@codeblog.com

    After a lot of developement testing… is there a way to “clear” all my defaults?

    Or a way to “view” all my defaults?

  • Donna

    I notice you “alloc” but never “release”.

    When is it needed… or specifically avoided???

  • Tammie

    Is there a way to save my prefs if the user just hits HOME and exits?

    Maybe put code in some kind of DidViewUnload function?

  • Tammie

    // This is suggested to synch prefs, but is not needed (I didn’t put it in my tut)
    [prefs synchronize];

    It’s not needed? But it’s “suggested” that I DO use it?
    When should I add it… or delete it?

    What does it even do? It “syncs” my prefs to what???

  • Graham F

    Is it possible to set initial default settings?

    If the user launches the application for the first time and has not yet had the chance to set the preferences, they are nil.

    I cannot find anything in the documentation about this?

    Cheers

    Graham

  • http://www.designsapling.com Jeremy White

    Personally, I like the video format with text a lot.

    I quickly read the text before I watch the video and see if I understand what I’ll be doing. It’s a good knowledge check.
    Then I watch the video, which is easy to follow and reinforces what I already remembered from reading the text.
    Then I read the text again to make sure it all sank in.

    Excellent job! I’m definitely getting the hang of iPhone development thanks to this site.

  • John

    I am looking to have an app developed for my company. Are you interested in contract work?

  • jpv

    Great Tutorial. I have a problem. Your tutorial works ok. But now i need to implement this with two xibs. i have the text field and the button in one xib. in another xib i have the label. i try all forms i could think but i could not make it work.

    Anyone helps please?

    thanks and sorry by my bad english

  • Olivia

    Brandon, outstanding tutorial! I am new to NSUserDefaults, but you explained this very well.

    How would this change if I implemented a UITextView instead of a UITextField?

  • Carlos

    I’m new to iPhone developing, and i have been checking out some of the tutorials you’ve written. Great material, very helpful!

    However, after trying this one (and double-checking i followed all the steps correctly, i haven’t been able to get it running. I build it without errors, but when the iphone simulator tries to run it, the screen appears black for a few seconds and then the application quits with the message “terminate due to uncaught exception”. Any idea of what is going on here?

    Thank you!

  • Carlos

    I’m new to iPhone developing, and i have been checking out some of the tutorials you’ve written. Great material, very helpful!

    However, after trying this one (and double-checking i followed all the steps correctly), i haven’t been able to get it running. I build it without errors, but when the iphone simulator tries to run it, the screen appears black for a few seconds and then the application quits with the message “terminate due to uncaught exception”. Any idea of what is going on here?

    Thank you!

  • neha

    Related question,
    Is it possible to access global settings. For e.g: current ringtone, ring volume, etc..

  • http://www.sun.ac.za Helmi

    Great tutorial…Assistance will be GREATLY appreciated re the following:

    I am trying to read / write floating point GPS golf data to 1) “data.plist” via dictionary plistDict. Testing with “defaults” works correct but not with a data.plist XML list.

    No problem with “defaults”:
    Writing:
    [defaults setFloat:loc.latitude forKey:keyLat];
    [defaults setFloat:loc.longitude forKey:keyLong];
    and then reading:
    float HoleLat = [defaults floatForKey:@"Hole1Lat"];
    float HoleLong = [defaults floatForKey:@"Hole1Long"];

    However when writing:
    [plistDict setObject:[NSNumber numberWithFloat:loc.latitude] forKey:keyLat];
    [plistDict setObject:[NSNumber numberWithFloat:loc.longitude] forKey:keyLong];
    is OK, but reading reading gives warning with:

    float HoleLong = [plistDict floatForKey:keyLong];
    float HoleLat = [plistDict floatForKey:keyLat];

    \Warning is:

    Warning: NSDictionary may not respond to -floatForKey. Incompatobel types in initialization.

    I cannot get to read data back from the data.plist ! Please help !
    Rgds Helmi

  • mesposito23

    How would I use these methods to keep count of how many times a button was pushed in an app? The counter would start at 0 and go up to 999,999,999.

    Thanks!

  • Wilbert

    Hi Brandon,

    How do you encrypt a password before saving it in NSUserDefaults?

    Could you point me to the right direction or some links on how to implement this?

    Thanks,
    Wilbert

  • Mike

    Is it possible to use these NSUserDefaults to save objects in an NSArray and display them on different views, connected through a UITableView?

  • Iya

    Thanks for this wonderful and easy tutorial.

  • olivia

    can brandon or anyone else explain or point me to another source on how i would modify this code so that i can save the index of an array when someone exits out of my app and loads the data from that index?

  • Ben

    “if(messageName == nil)” should really be
    “if(messageName == nil || [messageName isEqualToString: @""])” to keep the app from saying “Welcome, !”

  • mark funk

    how do i save the state of mw web pabe viewer

  • mark funk

    how do i save app state of a ui webview

  • Mike

    Perfect tutorial. Was working for an hour to get this to function. After watching your tutorial it all made sense and I had it working in minutes.

    Cheers

  • http://livecast.nl Jeffrey Snijder

    thanks, this works like a charme, i have on question, is it possible to clear this memory and start over?

    Jeffrey

  • http://www.jetscram.com Randy

    Thanks for the great post.

    @Jeffrey, in the iphone simulator on the toolbar under iphone simulator is: reset content and setting… give that a shot

  • nick

    Hey man, the xcode project download is missing.

    Nick

  • http://www.google.com noshad

    Great!
    i was searching for this!!!!!!!!!!!!

    it would be more better if u update it for savings the values in arrays.

  • Arman

    Great work!!!

    icodeblog is doing the superb job.

    Thanx icode

  • Gilad

    Short and simple, exactly what I was looking for.

    Thanks!

  • Claus Guttesen

    Thank you for posting this. Very usefull.

  • http://noneyet Omzig

    Hello… for some reason the Vid wont play.

  • http://noneyet Omzig

    Well, Crud after i posted this, it started playing. sorry

  • http://noneyet Omzig

    ZipFile wont download, says it isn’t there. The zip that has the code in it. I cannot get greeting.text to work. i get an error. says greeting undeclared.

  • http://noneyet Omzig

    ok, my bad again…

    i named my lable lblGreeting so i didnt have an object greeting.

    if (greetingName == nil) {
    lblGreeting.text = @”Welcome Guest!”;
    }

    Thanks.

  • Nathan

    Hi

    it’s really clear and neat tutorial, thanks brandon!

    Btw, i wonder if it can do the same to save a photo, and use it as wallpaper, coz i m searching the save photo tutorial and no luck, hope u can help.

    thanks a lot man!

  • Luis

    Great! clear tutorial!

    how i make it with views?

  • http://noneyet Omzig

    zipfile wont download, link broke

  • dbarrett

    Great job on the demo! Clear & concise… thanks so much.

  • http://blog.underplot.com Marin Todorov

    Brandon, you’re the best :)

    you’re stuff are detailed, but not overcomplicated, like them very much. I like more the text tuts, but anyway you do great job on everything.

    I laughed like crazy on the article about the iTunes’ iTennis … ‘the 12 year olds strike back’, lol but I’m sure you’ll be the star in ‘The return of the iCoders” :) )

    However, thumbs up man!
    Marin

  • http://arafat.blog.my Arafat

    I would like to know what method do you use when you want to save the game object. Example you have one class then you create an object. Are you using setObject?

  • http://kdp-tech.com Keyur Patel

    How could I go about using NSUserDefaults with Images? Please help and thanks in advance.

  • chris

    Brandon.

    Thanks for the tutorial. Great information here.

    I was just curious, is there a way to use NSUserDefaults to save the state of a UIButton? Basically, i’m working on an application where a button is disabled and displays an image with the user touches it. I just need to save this disabled state so that the next time the user launches the application, it will still be disabled and show the image.

    - Thanks again

  • Jill

    > Delegate Files – Each app has one delegate.

    One?
    Huh? We use many delegate files all through our apps.

  • Paula

    If I put my LOAD code inside viewDidLoad, where do I put my SAVE code?

  • JJ2010

    I like this tutorial. One question? I have used data to save and retrieve data using your tutorial and it works . How do I get another view in my app to do the same thing without affecting the nsdefaults setting in one specific view. Like I want to duplicated your example multiple times in different views in one app. I have tried adding another view and adding the similar code, even trying to change it so when you click the button for that one view it should save data entered for that view only? Can’t get it, some errors and other buttons to save text don’t work. Do you have any suggestions? Thank you.

  • Ken Wong

    hey babe, the sample code link is broken, please update.

    thanks a lot

  • http://www.helpdeskhome.co.uk Paul

    Hi this is a great tutorial, but i want to retrieve data from a file on a remote server (basically im going to update rugby scores on my own server then hopefully the iphone will load them automatically), any ideas on the remote bit ??? im new but not a noob :)

    great tutorial though man Awesome.

    Paul

  • http://www.seriousfunapps.com Samuel Tremblay

    Hey really great tutorial. I just want to let you know that the link to download the source is broken. I would really appreciate get the hand on it if possible. Thank you!

  • http://blog.insightvr.com John Harrison

    Just wanted to thank you for this tutorial. I used it to add save game functionality to my iPhone game, Battle for Vesta. I also posted my implementation on my blog if anyone is interested to see another example of NSUserDefaults in action.

  • http://blog.insightvr.com John Harrison

    // This is suggested to synch prefs, but is not needed (I didn’t put it in my tut)
    [prefs synchronize];

    It is worth mentioning that I found that I had to use the synchronize message to get the state to persist when I quit the application. Without it the state would only persist while the app was running.

  • http://numeral.com John Simon

    Just wanted to say thank you for all the tutorials.

    This code worked great for me right away.

    You saved me – once again – hours of lost time and frustration.

    THANK YOU!

  • paul

    it’s 6:15AM, my project is due at 9AM and you just solved all my problems.
    i’m buying you a pizza.

  • http://info.sean808080.com sean808080

    awesome tutorial. great job!

  • THéo

    HI!
    Where is the data stored please?

  • JJ2010

    This is a cool tutorial. And works well. I was wondering if you could do a video how to create your own keyboard or keyboard keys to work with UITextfields? I am making an app and I want my own keyboard keys?

  • http://www.vhelpu.blogspot.com Qasim Shah

    and what should i do for nagation controller.
    cz i wanna save and restore the last state of app for navigation page.

  • Claire

    I have the following scenario…

    On screen I have a button with a background image. When pressed, I want the background image to change..then when the app is closed, for the background image to stay the same.. If the user presses the button again, I then need it to switch back to its original state.

    Is this possible using this type of code?

    Thank you anyone for your help, this is all that is holding up my app.

    Claire

  • Sandip

    how to reteive a data from xml using xcode on iPhone?
    please tell me……

  • mihir

    One suggestion

    your site is taking too much time to open… due to the advertisement i guess… can’t you opt for another ad program..like google ad sense… It is light weight and takes no time to load… (I am telling this as your well wisher…. )

  • Darko

    Hi Brandon,

    Thank you very much for this beautiful tutorial! I have been trying to understand the usage of Default Preferences for like 3 days with no luck. After your video blog I was rolling with defaults in like minutes. If somebody from Apple is reading this blog they should take notes, because their site should have been this helpful…and it is NOT!

  • dpigera

    Great tutorial man.. Couldn’t be more concise :-)

  • iphone

    what if the key doesnot exists. mean lets suppose we have had not stored an integer with the key “myInt”. bt we try to get value of that integer by

    int i = [prefs integerForKey:@"myInt"];

    in this case what would be returned???

  • vincefried

    Amazing tut! But that doesn’t work on iOS 4! Can you help me?

  • Adam

    @vincefried

    Agreed. If you run this on a physical device and shut off the iphone, when you turn the phone back on, the data is not saved.

    For example:
    Lets say I want to keep track of a high score.
    When the player achieves a high score (lets say 5), the high score will be saved in memory because of ios4 multitasking, but if you shut your phone off you lose your score.

    Does anyone know how to write/read data and store it so data will be saved when the app is truly exited (ie: phone is shut off)?

  • Adam

    THANK YOU! I was wondering why this was not working. Will try this…

  • Adam

    Worked perfectly! Just need to tweak the placement of where exactly to put this line (i wasnt sure so I put it in the viewdidload (beginning and end) and also in the updatePrefs method, but it worked none the less. Thanks again!

  • http://funbyjohn.com/ Johannes Jensen

    The data still stays for me when I turn off my device, OS 4.0.0

    What I did, which this tutorial didn’t, was to also use [synchronize]; before loading the data.

  • http://www.omayr.blogspot.com Umair Akhtar

    that was awesome ! thanks a lot man.

  • http://www.arafatx.com MaXi32

    Hai you need to delete the application on your simulator / device first before you wanna clear the data.

    - MaXi32

  • domonique

    i can’t get it to work on iOS 4.1 at all.

    - (void)viewDidLoad {
    [super viewDidLoad];

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs synchronize];
    NSString *greetName = [prefs stringForKey:@"greeting"];

    if(greetName == nil) {
    greeting.text = @”Welcome guest!”;
    } else {
    greeting.text = [[NSString alloc] initWithFormat:@”Welcome %@”, greetName];
    }
    }

    what am i missing?

  • http://doganberktas.com/2010/10/16/data-storage-alternatives-on-ios-in-a-nutshell/ Data Storage Alternatives on iOS (in a Nutshell) | dogan kaya berktas

    [...] Tutorial (link) [...]

  • Alberto

    This tutorial is really very good man! But, why don’t save in IOS? ;-/

  • http://threebrain.com threebrain

    haaaay! thank you so much for this tutorial. I was having a very hard time figuring this out today and was getting discouraged as well as depressed and angry. Right when i was about to give up your tutorial showed me the way! :-D Now i got my scores saving so when the app opens back up booyah! You’re a great teacher indeed. Nice concise lesson.

  • Janhavi

    Great Yar!!!! No more questions….
    ‘Thanks a lot’!!!!!!

  • http://NatashaZPais.net john.doh@usa.net

    Very nice. Short very specifically targeted tutorial, concise, clear, with no hesitation and muddying around. You truly are a great teacher. Thanks!

  • http://www.worldoftrade.com/ Rolex Oyster

    Thanks for the sharing of such information we will pass it on to our readers.
    This is a great reading.
    Thanking you Nice post.

  • http://web.me.com/tutorials.universe/ Kimo

    Great Tutorial. This is exactly what I was looking for ;)
    Thanks ;)

  • S2c2k7

    All links are broken.

  • Anonymous

    Links should be fixed now! Thanks for the heads up.

  • Orubin

    Still broken. The code sample leads to a page that says: “Not found!
    Sorry, no posts matched your criteria.!!”

  • Necixy

    Synchronization is a must!!!!
    Without it you can get random results….

  • Hidde

    All links are broken

  • Terry

    hi, thanks, this was helpful.

  • arod

     Excellent reference, this helped me a lot, thanks.

  • http://www.facebook.com/people/Kunal-Gandhi/731782800 Kunal Gandhi

    Thanks Bro !! You have made my day … God Bless You !

  • http://www.facebook.com/people/Kunal-Gandhi/731782800 Kunal Gandhi

    and ya .. Guys .. synchronize is a must , please take into consideration as without it I was not able to save and get my values but after I added synchronize it worked perfectly !!

  • Vikramt87

     ya krunal its working

  • http://profiles.google.com/hwsale herbwhole sale

    pura sun – Post interesting and thanks for sharing. Some things in here I have not thought about before. Thanks for doing the cool-down, which is really good written. I will refer more friends about this. This is one of the charismatic, informatics blog and a good book about life at most that have been described in the special features to help readers and visitors. All information found here is genuine and realistic.

  • Gbm Gee

    can i get the source code for the example….bcos i am new to iphone app dev.
    i need to creato the settings for my app to check wether the file is there or not…..

  • Gbm Gee

    weather the prefs is temporary storage or permanent storage.
    if i save the login credentials and i quit the app, then i need to use the app,
    so i need to give the login credentials or i can take the prefs value which i stored.

  • Gbm Gee

    thankz for giving the article….i need a clarification…
    weather the prefs is temporary storage or permanent storage.
    if i save the login credentials and i quit the app, then i need to use the app,
    so i need to give the login credentials or i can take the prefs value which i stored.

  • Premal

    Nice and brief article. Thanks a lot! 

  • CRP

    great article.  I cant download the source code….takes me to an invalid page.  Would be nice to get that!

  • H Hellohello

    “great article.  I cant download the source code….takes me to an invalid page.  Would be nice to get that!”Ditto.

  • rao

    hello i have used nsuserdefault for storing the image name from one of the controller (on clik of a button ) for setting the background of  rest of the controllers based on the image name .I am synchronising the default.so everything works fine.BUT the problem arises when i open allocation tool whenever i am changing the image name and synchronising the default on click of button the allocation shows increase in memory allocation by near about 1 MB .
       So if anyone knows why this happen and the solution then please let me know?

  • Selman

    Hi,

    I have to ask something;
     if I use NSUserDefaults or SQlite for login credentials what happens when I relase an update and user upadates the app
     Does he/she losses the stored data in NSUserDefaults or SQlite?

  • Guest

    Where would I put my “LOAD and SAVE defaults” code blocks?
    In viewDidLoad and viewDidUnload?
    (It doesn’t work.)

  • madhuri chivukula

    Actually I need someone’s assistance! I am very new to this.could u please drive me in a right path?
    I am actually designing a sign up view . I need to save all the data entered in the text fields.
    My another question is i am creating a table view with an array.if i select some data/array using check mark,i want all the selected array to store . how can i do that? actually how does it work? Looking forward for a reply.

  • H Karaki

    Hello guys 

    I have many view controllers in my project , how can I retrieve data saved in the third view controllers to the last view controller so I can display it ???

    please I need any help

  • Guest

    When can these values get reset? On mobile restart or something?

  • Neerajkiet

    nice tut..

  • k4

    no links man…broken!!!

  • Sundeep sharma

    can we save more then one object to same key like sqlite

  • Nihas n a

    thanks….

  • Slava_zubrin

    As far a I know now we cant. Just the unique value userDefaults for unique key. That is why usually every key begins with application name.

  • Joshua Davies

    Thank you – this is the sort of thing you’d THINK Apple would make easily accessible in their own documentation, but after poking around there for 20 minutes I gave up and googled this.  Your blog was the first entry, which was exactly what I was looking for – thanks!

blog comments powered by Disqus