Regardless of Android, H5, or PC, data needs to be saved locally to obtain requirements for subsequent use. For example, The Android version provides SharedPreferences for saving data, and the iOS version provides NSUserDefaults.

The data structures that can be saved in NSUserDefaults are:

  1. Nsstrings string
  2. NSNumber digital
  3. NSArray array
  4. NSDictionary dictionary
  5. NSDate date
  6. NSData Binary data

If you want to save custom objects, you need to archive the objects as NSData and then save them. There are two ways to save a custom object to SharedPreferences:

  1. One is to convert the object to JSON and save it as a string.
  2. ObjectOutputStream serializes an object, saves it, and deserializes it back when it is retrieved.

IOS archiving should be similar to Java’s serialization and deserialization mechanism.

Basic Api

  • Get NSUserDefaults instances
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
Copy the code
  • Store the data
// Make sure to save the object (object) and key (defaults)setObject:object forKey:key]; // For example, save the string [defaults]setObject:@"Wally" forKey:@"NAME"]; // Save the Number object [defaults]setObject:number forKey:@"NUMBER"];
Copy the code
  • To get the data
Object = [defaults objectForKey:key]; // For example, get the saved string id name = [defaults objectForKey:@"NAME"];
NSLog(@"Name: %@", name); Num = [defaults objectForKey:@"NUMBER"];
NSLog(@"num: %@", num);
Copy the code
  • If an exception is thrown immediately after the data is saved, data may be lost. Therefore, you are advised to call Synchronize immediately after the data is saved.
[defaults synchronize];
Copy the code
  • Delete the data
// Delete saved values with key [defaults removeObjectForKey:@"ARRAY"];
Copy the code

Quick Api

NSUserDefaults can store all six of these types, and Apple’s dad gave us a way to convert them directly, so you don’t have to force code every time.

  1. storage
// Store Int values [defaults]setInteger:123 forKey:@"INT"]; // Store Boolean values [defaults]setBool:YES forKey:@"BOOL"]; // Store the float type [defaults]setFloat: 3.14forKey:@"FLOAT"]; NSArray* arr = [NSArray arrayWithObjects:@"Wally"The @"Barry"The @"Rose", nil];
[defaults setObject:arr forKey:@"ARRAY"];
Copy the code
  1. To obtain
// get Int NSLog(@)"int: %ld", [defaults integerForKey:@"INT"]); // get BOOL NSLog(@)"bool: %d", [defaults boolForKey:@"BOOL"]); // get the floating point value NSLog(@"float: %f", [defaults floatForKey:@"FLOAT"]); NSArray* arr = [defaults objectForKey:@"ARRAY"];
NSLog(@"% @", arr);
Copy the code

Save custom objects

If you want to save a custom object, you need to convert the object to NSData before saving it. For example, to save user login information and user name and password, the operation is divided into the following steps:

  1. Define user information model and implement NSCoding protocol.
// file: fsuser.h@interface FSUser: NSObject<NSCoding> /** *username */ @property(nonatomic, strong) NSString *username; /** *password */ @property(nonatomic, strong) NSString *password; /** * get all attributes of the object into a string */ - (NSString *) toString; @endCopy the code
  1. In NSCoding protocol, initWithCoder method and encodeWithCoder method, initWithCoder method is used to learn files and recover objects with data, initWithCoder method is used to archive objects.
m@implementation FSUser /** * return */ - (instanceType)initWithCoder:(NSCoder *)coder {self = [super init];if (self) {
        self.username = [coder decodeObjectForKey:@"_username"];
        self.password = [coder decodeObjectForKey:@"_password"];
    }
    returnself; } /** * archive */ - (void)encodeWithCoder:(NSCoder *)coder {[coder encodeObject:_usernameforKey:@"_username"];
    [coder encodeObject:_password forKey:@"_password"];
}

- (NSString *)toString {
    return[NSString stringWithFormat:@"Username: %@, password: %@", _username, _password];
}

@end
Copy the code
  1. Archive (serialization) : use NSKeyedUnarchiver, call archivedDataWithRootObject method, the object file.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; // Store custom object FSUser *user = [[FSUser alloc] init]; user.username = @"Wally";
user.password = @"123456"; / / filing NSData * userData = [NSKeyedArchiver archivedDataWithRootObject: user]. [defaultssetObject:userData forKey:@"USER"];
Copy the code
  1. Unfile (deserialize) : Unfile the object using NSKeyedUnarchiver and call the unarchiveObjectWithData method.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; NSData *userData = [defaults objectForKey:@"USER"]; / / solution, restore object FSUser * user = [NSKeyedUnarchiver unarchiveObjectWithData: userData]; // Output: user name: Wally, password: 123456 NSLog(@"% @", [user toString]);
Copy the code