When we develop the app, we will inevitably store some data locally, nsuserdefaults is a system-provided class for data storage, this article will introduce some nsserdefazults usage.
More information: https://my.oschina.net/u/1245365/blog/294449
First of all, for the novice nsuserdefaults what is it???
Nsuserdefaults is a singleton provided by the iOS system, with only one instance object in the whole program, he can be used for permanent data storage, and simple and practical, so we all prefer this way.
1. Get Nsuserdefault: by Standarduserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
2. Storage mode:
Nsuserdefaults a singleton has been key-value to store a series of settings, key is the name, and value is the corresponding data. Save Data (Objectforkey:), Fetch data (Setobject:forkey:)
The data types stored are: nsdata,nsstring,nsnumber,nsdate, nsarray,nsdictionary. If you want to store the image, you cannot store it directly, you need to archive the image to the NSData type first.
3. Access different types of data:
Save:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];[defaults setObject:@”jack“ forKey:@"firstName"];[defaults setInteger:10 forKey:@"Age"];UIImage *image =[UIImage imageNamed:@"somename"];NSData *imageData = UIImageJPEGRepresentation(image, 100);//把image归档为NSData[defaults setObject:imageData forKey:@"image"];[defaults synchronize];
Where the method synchronize is to force the storage, it is not necessarily necessary, because this method will be called by default in the system, but you are sure to store it immediately, it is possible
Read
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];NSString *firstName = [defaults objectForKey:@"firstName"]NSInteger age = [defaults integerForKey:@"Age"];NSData *imageData = [defaults dataForKey:@"image"];UIImage *image = [UIImage imageWithData:imageData];
Note: The same key assignment is approximately equal to one overwrite, to guarantee the uniqueness of each key
Several other ways to access different types of data:
setBool:forKey:- setFloat:forKey:- setInteger:forKey:- setDouble:forKey:- setURL:forKey:
My simple application in the project:
Through the appdelegate.
-(void) Registerdefaults: Method to initialize,
----of persistent iOS data storage nsuserdefaults