Usage of Nsuserdefaults in iOS (lightweight local data store)

Source: Internet
Author: User

Nsuserdefaults is suitable for storing lightweight local data, such as the data to save a login interface, user name, password, and so on, individuals feel that using nsuserdefaults is preferred. The next time you log in, you can read the last login information directly from the Nsuserdefaults.

Because if you use the Plist file you created, you also have to display the creation of files, read files, very troublesome, but with nsuserdefaults do not care about these things, like reading a string, directly read it.

The data formats supported by Nsuserdefaults are: NSNumber (Integer, Float, Double), Nsstring,nsdate,nsarray,nsdictionary,bool type. It's practical.

Nsuserdefaults is very convenient and easy to read. Here is an example to see how to use: (PS: More details can also refer to the official document HA)

The main ViewController.h file is to put a few controls to display the stored data:

#import "ViewController.h"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload{[Super Viewdidload];  [Self savensuserdefaults]; //call this method to store a variety of data in NSUSERDEFAUTLS, defined below[Self readnsuserdefaults];//call this method to read a variety of data from NSUSERDEFAUTLS, defined below}- (void) viewdidunload{[txtnsstring release]; Txtnsstring=Nil;    [Txtnsdate release]; Txtnsdate=Nil;    [Txtnsarray release]; Txtnsarray=Nil;    [Txtnsdictionary release]; Txtnsdictionary=Nil;    [Txtinteger release]; Txtinteger=Nil;    [Txtfloat release]; Txtfloat=Nil;    [Txtdouble release]; Txtdouble=Nil;    [Super Viewdidunload]; //Release Any retained subviews of the main view.}-(BOOL) shouldautorotatetointerfaceorientation: (uiinterfaceorientation) interfaceorientation{return(Interfaceorientation! =uiinterfaceorientationportraitupsidedown);}- (void) Dealloc {[txtnsstring release];    [Txtnsdate release];    [Txtnsarray release];    [Txtnsdictionary release];    [Txtinteger release];    [Txtfloat release];    [Txtdouble release]; [Super Dealloc];}//save data to Nsuserdefaults-(void) savensuserdefaults{NSString*mystring =@"Enuola"; intMyinteger = -; floatMyfloat =50.0f; DoubleMyDouble =20.0; NSDate*mydate =[NSDate Date]; Nsarray*myarray = [Nsarray arraywithobjects:@"Hello",@" World", nil]; Nsdictionary*mydictionary = [Nsdictionary dictionarywithobjects:[nsarray arraywithobjects:@"Enuo",@" -", nil] Forkeys:[nsarray arraywithobjects:@"name",@" Age", Nil]]; //Store all of the above data in NsuserdefaultsNsuserdefaults *userdefaults =[Nsuserdefaults Standarduserdefaults]; //when storing, other than the NSNumber type uses the corresponding type unexpectedly, the others are using Setobject:forkey:[Userdefaults Setinteger:myinteger Forkey:@"Myinteger"]; [Userdefaults setfloat:myfloat Forkey:@"myfloat"]; [Userdefaults setdouble:mydouble Forkey:@"MyDouble"]; [Userdefaults setobject:mystring Forkey:@"myString"]; [Userdefaults setobject:mydate Forkey:@"mydate"]; [Userdefaults setobject:myarray Forkey:@"MyArray"]; [Userdefaults setobject:mydictionary Forkey:@"MyDictionary"]; //It is recommended to store the synchronization to disk, but it is not necessary[Userdefaults Synchronize]; }//reading data from the Nsuserdefaults-(void) readnsuserdefaults{Nsuserdefaults*userdefaultes =[Nsuserdefaults Standarduserdefaults]; //read the data into each label//reading data of integer int typeNsinteger Myinteger = [Userdefaultes integerforkey:@"Myinteger"]; Txtinteger.text= [NSString stringWithFormat:@"%d", Myinteger]; //reading data of float type float    floatMyfloat = [Userdefaultes floatforkey:@"myfloat"]; Txtfloat.text= [NSString stringWithFormat:@"%f", Myfloat]; //reading a double type of data    DoubleMyDouble = [Userdefaultes doubleforkey:@"MyDouble"]; Txtdouble.text= [NSString stringWithFormat:@"%f", MyDouble]; //reading NSString Types of dataNSString *mystring = [Userdefaultes stringforkey:@"myString"]; Txtnsstring.text=myString; //reading data of the NSDate date typeNSDate *mydate = [Userdefaultes valueforkey:@"mydate"]; NSDateFormatter*DF =[[NSDateFormatter alloc] init]; [DF Setdateformat:@"YYYY-MM-DD HH:mm:ss"]; Txtnsdate.text= [NSString stringWithFormat:@"%@", [DF Stringfromdate:mydate]]; //reading data from an array of type NsarrayNsarray *myarray = [Userdefaultes arrayforkey:@"MyArray"]; NSString*myarraystring =[[NSString alloc] init];  for(NSString *strinchMyArray) {NSLog (@"str=%@", str); Myarraystring= [NSString stringWithFormat:@"%@  %@", myarraystring, str]; [Myarraystring Stringbyappendingstring:str];//[myarraystring stringbyappendingformat:@ "%@", str];NSLog (@"myarraystring=%@", myarraystring); } Txtnsarray.text=myarraystring; //reading data from a dictionary type Nsdictionary typeNsdictionary *mydictionary = [Userdefaultes dictionaryforkey:@"MyDictionary"]; NSString*mydicstring = [NSString stringWithFormat:@"name:%@, age:%d", [MyDictionary Valueforkey:@"name"], [[MyDictionary Valueforkey:@" Age"] [IntegerValue]]; Txtnsdictionary.text=mydicstring;}@end

OK, run it, can you see the various data in the Xib file is already tied up?

Run again, you can put viewdidload in the [self savensuserdefaults]; This line is commented out, allowing the program to read directly without storing the data, discovering that the previously saved data can still be read to the interface.

Hehe, very simple, so it can be the implementation of data storage.

Here's how it works:

You may ask a question: Where does the NSUSERDEFAUTLS store the data??? I have not shown the specified path??? Very confused ....

Data stored with Nsuserdefaults still exists the next time the program runs, where does it store the data? How can I clear?

In fact it is stored in a plist file built into the application, which can be seen according to the path. For example, this is your program sandbox location.
/userslibrary/application support/iphonesimulator/4.1/applicati*****/29788e40-af47-45a0-8e92-3ac0f501b7f4/, (This is where the application corresponds on the Mac)
There is a/library/prefereces, there is a plist file, stored is your userdefaults
If you want to erase it, use Removeobjectforkey or delete the sandbox, which is your application and then reinstall it.

Usage of Nsuserdefaults in iOS (lightweight local data store)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.